16

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??

2
  • 9
    sigh This must be one of the most frequent errors ever. When you load an XML document into a SimpleXmlElement, the root node is the SimpleXmlElement, e.g. $xml = <main>. Commented Apr 8, 2011 at 10:35
  • 1
    Thanks for the explanation Gordon. Commented Apr 8, 2011 at 10:37

3 Answers 3

31
$xml = new SimpleXMLElement($xml);
$this->xmlcode = (string) $xml->parent[0]->child1;
Sign up to request clarification or add additional context in comments.

1 Comment

Problem solved for me by adding type (string) of (float) for example.
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); 

1 Comment

SimpleXml can do XPath queries. There is no need to convert to DOM to do so. The only advantage of using evaluate is when getting typed results, which your example clearly doesn't do.
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.