Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleXML get node value

Tags:

php

xml

simplexml

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

like image 331
priktop Avatar asked Apr 08 '11 10:04

priktop


2 Answers

$xml = new SimpleXMLElement($xml);
$this->xmlcode = (string) $xml->parent[0]->child1;
like image 160
vartec Avatar answered Nov 15 '22 00:11

vartec


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); 
like image 2
Paul Avatar answered Nov 15 '22 02:11

Paul