John Davidson

Cannot read the subnodes with PHP of an XML file

0 comments
Message:




I am reading an XML file with PHP as follows:

$this->dom->loadHTML('<?xml encoding="UTF-8">' . $strbody );
$xp = new \DOMXPath($this->dom);

foreach( $xp->query('//div | //ul | //ol') as $node) {
array_push($nodes, $node);
}
// Further processing of the individual elements.
// "2 loop".
foreach( $nodes as $node)
{
echo "node: " . print_r($node, true) . PHP_EOL;
}

Via the 2 loop I want to access sub-knead.

From this node I can output the attributes with:


foreach ( $node->attributes as $nodeValue )
{
echo "attributes: ".print_r($nodeValue, true).PHP_EOL;
}

Or I can also print out the child nodes:


foreach ( $node->childNodes as $nodeValue )
{
echo "childNodes: ".print_r($nodeValue, true).PHP_EOL;
}

But how can I access the child nodes?

Here is the structure of the XML file:


<startxml system="https://bspurl.de" sprache="DE">
<inhalt bez="body" sprache="DE">
<objekt type="xhtml">
</div class="text">
sadf gfew
</div>
<div class="h2">Überschrift</div>
<div class="text">
<span class="bold">Weitere Infos:</span>
</div>
</div class="text">
asf 43 rfedv34asd
</div>
</objekt>
</inhalt>
</startxml>

I need to access the span (< span class="bold">Weitere Infos:< /span >) element, how?


Thanks



My Answer:
xml = simplexml_load_file('file.xml');

foreach($this->xml->children() as $child){
echo $child->getName() . ": " . $child . "
";
}

This code will read the top-level nodes of the XML file and display their names and values. If you want to read subnodes, you will need to access them recursively by iterating through each node's children. Here is an example of how you can read subnodes with PHP:

function readSubnodes($node){
foreach($node->children() as $child){
echo $child->getName() . ": " . $child . "
";
readSubnodes($child);
}
}

readSubnodes($this->xml);

This function will recursively read all subnodes of the XML file and display their names and values. You can call this function on the top-level node to read all subnodes.

Rate this post

3 of 5 based on 3647 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us