Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the innerText of an element with SimpleXml

Tags:

php

simplexml

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?

like image 438
noClue Avatar asked Oct 10 '12 14:10

noClue


2 Answers

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;
like image 187
Gordon Avatar answered Sep 24 '22 17:09

Gordon


echo (string)$xml->body;

work for me

like image 29
Wasim A. Avatar answered Sep 24 '22 17:09

Wasim A.