Welcome to the Cookbook

loading...

8.4.1 Xml parsing

There is no translation yet for this section. Please help out and translate this.. More information about translations

Parsing Xml with the Xml class requires you to have a string containing the xml you wish to parse.

$input = '<' . '?xml version="1.0" encoding="UTF-8" ?' . '>
    <container>
        <element id="first-el">
            <name>My element</name>
            <size>20</size>
        </element>
        <element>
            <name>Your element</name>
            <size>30</size>
        </element>
    </container>';
$xml = new Xml($input);
  1. $input = '<' . '?xml version="1.0" encoding="UTF-8" ?' . '>
  2. <container>
  3. <element id="first-el">
  4. <name>My element</name>
  5. <size>20</size>
  6. </element>
  7. <element>
  8. <name>Your element</name>
  9. <size>30</size>
  10. </element>
  11. </container>';
  12. $xml = new Xml($input);

This would create an Xml document object that can then be manipulated and traversed, and reconverted back into a string.

With the sample above you could do the following.

echo $xml->children[0]->children[0]->name;
// outputs 'element'

echo $xml->children[0]->children[0]->children[0]->children[0]->value;
// outputs 'My Element'

echo $xml->children[0]->child('element')->attributes['id'];
//outputs 'first-el'
  1. echo $xml->children[0]->children[0]->name;
  2. // outputs 'element'
  3. echo $xml->children[0]->children[0]->children[0]->children[0]->value;
  4. // outputs 'My Element'
  5. echo $xml->children[0]->child('element')->attributes['id'];
  6. //outputs 'first-el'

In addition to the above it often makes it easier to obtain data from XML if you convert the Xml document object to a array.

$xml = new Xml($input);
// This converts the Xml document object to a formatted array
$xmlAsArray = Set::reverse($xml);
// Or you can convert simply by calling toArray();
$xmlAsArray = $xml->toArray();
  1. $xml = new Xml($input);
  2. // This converts the Xml document object to a formatted array
  3. $xmlAsArray = Set::reverse($xml);
  4. // Or you can convert simply by calling toArray();
  5. $xmlAsArray = $xml->toArray();