Jebediah Jebediah -5 years ago 112
PHP Question

SimpleXMLElement: get the exact positions of different tags into the same parent

I have this XML (simplified):

<?xml version="1.0" encoding="UTF-8"?>
<p>Example text</p>
<p>Another text</p>
<img l:href="imagehref">
<p>Some other text</p>

I would like to make a readable text from this, so I'm parsing it with SimpleXMLElement and get this:

object(SimpleXMLElement) {
array(3) {
array(1) {
object(SimpleXMLElement) {

All tags are grouped by name, so i cannot determine where the picture is located into the text – just that it exists.

The question: is there any way to get the exact sequence of tags in
? Like this:

[0] => 'p',
[1] => 'p',
[2] => 'img',
[3] => 'p'

so that i could transform them into HTML in correct order?

Answer Source

You could just iterate over the child nodes of every <section> tag.

// Assumes your string is loaded, e.g.
// $xml = simplexml_load_string($xml_string);
foreach($xml->xpath('//section') as $section) {
    foreach($section->children() as $node) {
        echo $node->getName(), "\n";

You can see that this outputs:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download