0

I create simple xml:

<?xml version="1.0" encoding="UTF-8"?>
<s>
  <s n="level1">
    <c n="level2">
        <s>
            <s n="level4">
                <a n="name1" />
                <a n="name2" />
                <a n="name3">20160826</a>
                <a n="name4">01</a>
                <a n="name5">01</a>
            </s>
            <a n="name6">1</a>
            <a n="name7" />
            <a n="name8" />
            <a n="name9">6</a>
        </s>
    </c>
  </s>
</s>

Then a load this file as:

$xmlObject = simplexml_load_file($filepath); 
$aCollection = $xmlObject->xpath('/s/s[@n="level1"]/c[@n="level2"]/s');
print_r($aCollection);

As result I have next data:

Array(
    [0] => SimpleXMLElement Object (
            [s] => SimpleXMLElement Object 
                    [@attributes] => Array (
                            [n] => level4
                        )
                    [a] => Array (
                            [0] => SimpleXMLElement Object (
                                    [@attributes] => Array (
                                            [n] => name1
                                        )
                                )
                            [1] => SimpleXMLElement Object (
                                    [@attributes] => Array (
                                            [n] => name2
                                        )
                                )
                            [2] => 20160826
                            [3] => 01
                            [4] => 01
                        )
                )
            [a] => Array (
                    [0] => 1
                    [1] => SimpleXMLElement Object (
                            [@attributes] => Array (
                                    [n] => name7
                                )
                        )
                    [2] => SimpleXMLElement Object (
                            [@attributes] => Array (
                                    [n] => name8
                                )
                        )
                    [3] => 6
                )
        )
)

All nodes with values are disappear. There are only empty nodes in result.

I would like to go through each $aCollection (result array) element and find nodes by attribute value in each element ( like $element->xpath('/a[@n="name6"]') ).

But now there isn't nodes with attribute value "name6" and "name9".

1 Answers1

1

Don't use print_r to inspect SimpleXML objects. Everything is still there, you just need to access it. Try this:

foreach ($xmlObject->xpath('/s/s[@n="level1"]/c[@n="level2"]/s') as $element) 
{
    if ($element->xpath('./a[@n="name6"]')) {
        // Do something with $element->xpath('./a[@n="name6"]')[0]
    }
}

See https://eval.in/1008597

iainn
  • 16,826
  • 9
  • 33
  • 40