I'm still fairly new with SimpleXml. What I'm trying to do:
I have many xml-files, which are build about the same. My problem is that sometimes there are more nodes in my target node. Example (trying to get body):
xml-file 1
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<firstname>My name is WHAT</firstname>
<lastname>My name is WHO</lastname>
<body>My name is CHIKA CHIKA Slim-Shady</body>
</note>
xml-file 2
<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<firstname>My name is WHAT</firstname>
<lastname>My name is WHO</lastname>
<body><b>My name is CHIKA CHIKA Slim-Shady</b></body>
</note>
I can get the text in the first file with no problem:
$xml = simplexml_load_file("filename.xml");
echo $xml->note->body;
But when I try to do the same in the second file I get nothing back.
How can I get php to only spit out the text in a node, without regard to any additional nodes within the target node?
In order for the traversal
echo $xml->note->body;
To work, your markup would need to be
<note>
<note>
<body>
…
To avoid such errors, it is good practise to name the variable you simplexml_load_file
into after the root element in the markup, e.g.
$note = simplexml_load_string($xml);
To get the "innerText" of a SimpleXmlElement you can do:
echo strip_tags($note->body->asXml());
the asXML()
method will give you the "outerXML" which you then remove with strip_tags
.
The alternative would be importing the node into DOM and then getting it's nodeValue
echo dom_import_simplexml($note->body)->nodeValue;
echo (string)$xml->body;
work for me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With