Note that there are some explanatory texts on larger screens.

plurals
  1. POiterating over unknown XML structure with PHP (DOM)
    primarykey
    data
    text
    <p>I want to write a function that parses a (theoretically) unknown XML data structure into an equivalent PHP array. </p> <p>Here is my sample XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;content&gt; &lt;title&gt;Sample Text&lt;/title&gt; &lt;introduction&gt; &lt;paragraph&gt;This is some rudimentary text&lt;/paragraph&gt; &lt;/introduction&gt; &lt;description&gt; &lt;paragraph&gt;Here is some more text&lt;/paragraph&gt; &lt;paragraph&gt;Even MORE text&lt;/paragraph&gt; &lt;sub_section&gt; &lt;sub_para&gt;This is a smaller, sub paragraph&lt;/sub_para&gt; &lt;sub_para&gt;This is another smaller, sub paragraph&lt;/sub_para&gt; &lt;/sub_section&gt; &lt;/description&gt; &lt;/content&gt; </code></pre> <p>I modified this DOM iterating function from devarticles:</p> <pre><code>$data = 'path/to/xmldoc.xml'; $xmlDoc = new DOMDocument(); #create a DOM element $xmlDoc-&gt;load( $data ); #load data into the element $xmlRoot = $xmlDoc-&gt;firstChild; #establish root function xml2array($node) { if ($node-&gt;hasChildNodes()) { $subNodes = $node-&gt;childNodes; foreach ($subNodes as $subNode) { #filter node types if (($subNode-&gt;nodeType != 3) || (($subNode-&gt;nodeType == 3))) { $arraydata[$subNode-&gt;nodeName]=$subNode-&gt;nodeValue; } xml2array($subNode); } } return $arraydata; } //The getNodesInfo function call $xmlarray = xml2array($xmlRoot); // print the output - with a little bit of formatting for ease of use... foreach($xmlarray as $xkey) { echo"$xkey&lt;br/&gt;&lt;br/&gt;"; } </code></pre> <p>Now, because of the way I'm passing the elements to the array I'm overwriting any elements that share a node name (since I ideally want to give the keys the same names as their originating nodes). My recursion isn't great... However, even if I empty the brackets - the second tier of nodes are still coming in as <em>values</em> on the first tier (see the text of the description node).</p> <p>Anyone got any ideas how I can better construct this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload