user889030 user889030 - 3 months ago 15
PHP Question

SimpleXMLElement object parsing

i have xml file

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<comments
xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<authors>
<author></author>
</authors>
<commentList>
<comment authorId="0" ref="G2">
<text>
<t xml:space="preserve"> test comment 1</t>
</text>
</comment>
<comment authorId="0" ref="G4">
<text>
<t xml:space="preserve"> test comment 2</t>
</text>
</comment>
</commentList>
</comments>


i load it through SimpleXMLElement php function

$com = new SimpleXMLElement('data.xml');


when i print_r($com) i get

SimpleXMLElement Object
(
[authors] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
()
)
[commentList] => SimpleXMLElement Object
(
[comment] => Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[authorId] => 0
[ref] => G2
)
[text] => SimpleXMLElement Object
([t] => test comment 1)
)
[1] => SimpleXMLElement Object
(
[@attributes] => Array
(
[authorId] => 0
[ref] => G4
)
[text] => SimpleXMLElement Object
(
[t] => test comment 2
)
)
)
)
)


i want to read comments using ref values , i tried to read value of G2 like

echo $value = (string) $comments->commentList->comment[0]->ref['G2'];


but no success , any idea how to read values through ref values like G2 , G4

Answer

If you want to get the comment text related to any comments that have ref="G2", then you'll do this. Iterate through each comment element, get the value of the ref attribute, check it against the target value, and if it matches, get the text value.

$xmlElement = new SimpleXMLElement($myXML);

foreach($xmlElement->commentList->comment as $comment)
{
    if($comment["ref"] == "G2")
    {
        echo $comment->text->t;
        // optionally echo line break or some other formatting
    }
}

Live Example