SimpleXML get node value

Say I have this following XML structure:

<?xml version="1.0" encoding="UTF-8"?>
<main>
    <parent>
        <child1>some value</child1>
        <child2>another value</child2>
    </parent>
</main>

I made a variable of the XML and now I want to get the values of child1, so I use SimpleXML:

$xml = new SimpleXMLElement($xml);
$this->xmlcode = (string) $xml->main->parent->child1;

But I get this message: Notice: Trying to get property of non-object in /x.php on line x

I also tried it with $xml->parent->child1, but no success.

Anyone??

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

$xml = new SimpleXMLElement($xml);
$this->xmlcode = (string) $xml->parent[0]->child1;

Solution 2

A good example of using XPath with php for the SimpleXMLElement can be found here
http://www.php.net/manual/en/class.simplexmlelement.php#95229

// Find the topmost element of the domDocument
$xpath = new DOMXPath($xml);
$child1 = $xpath->evaluate('/main/parent/child1')->item(0); 

Solution 3

Variant for xpath (Also how to get content of node having dashes in name):

<?xml version="1.0" encoding="UTF-8"?> <main>
<parent>
    <child-1>some value</child-1>
    <child-2>another value</child-2>
</parent> </main>
$xml = simplexml_load_string($content);
$node_value= (string)$xml->xpath('parent/child-1')[0];

result of $node_value:

"some value"

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply