cjhill
cjhill

Reputation: 1064

SimpleXML: Parsing nodes with value and other nodes

Having an issue parsing some XML from within PHP. A node contains a node value and other nodes. Is there a way to parse both?

I am consuming this via an API so cannot control the output.

<?php
$xml = '<root>
    <foo>
        bar
        <foobar>Foobar</foobar>
    </foo>
</root>';

$data = new \SimpleXMLElement($xml);
var_dump($data);

Will output:

object(SimpleXMLElement)#3 (1) {
  ["foo"]=>
  string(11) "bar"
}

Upvotes: 0

Views: 25

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

You just need to treat the data values as strings and you can access them as normal elements.

$data = new \SimpleXMLElement($xml);
echo "foo=".trim($data->foo).PHP_EOL;  // trim() to remove excess whitespace
echo "foo XML=".$data->foo->asXML().PHP_EOL;
echo "foobar=".(string)$data->foo->foobar;

Will output...

foo=bar
foo XML=<foo>
        bar
        <foobar>Foobar</foobar>
    </foo>
foobar=Foobar

Upvotes: 1

Related Questions