Search code examples
phparraysxmlstarlet

Get node content from xml file and transform it into php array?


I'm looking for solution to extract some node from large xml file (using xmlstarlet http://xmlstar.sourceforge.net/) and then parse this node to php array.

elements.xml

<?xml version="1.0"?>
<elements>
  <element id="1" par1="val1_1" par2="val1_2" par3="val1_3">
    <title>element 1 title</title>
    <description>element 1 description</description>
  </element>
  <element id="2" par1="val2_1" par2="val2_2" par3="val2_3">
    <title>element 2 title</title>
    <description>element 2 description</description>
  </element>
</elements>

To extract element tag with id="1" using xmlstarlet I'm executing this shell command...

xmlstarlet sel -t -c "/elements/element[id=1]" elements.xml

This shell command outputs something like this...

<element id="1" par1="val1_1" par2="val1_2" par3="val1_3">
  <title>element 1 title</title>
  <description>element 1 description</description>
</element>

How could I parse this shell output into php array?

Thank you.


I've found http://php.net/manual/en/function.simplexml-load-string.php pretty useful. This SimpleXML function will convert extracted piece of XML to SimpleXML object.


Solution

  • you could always take the new outputted xml and use simplexml like:

    $data = '<element id="1" par1="val1_1" par2="val1_2" par3="val1_3">
    <title>element 1 title</title>
    <description>element 1 description</description>
    </element>';
    
    
    $xml = simplexml_load_string($data);
    echo $xml->title; //access title
    echo $element_ID = $xml->attributes()->id; //access elements attributes by name
    

    and now $xml is the array you need