lolalola
lolalola

Reputation: 3823

xml + xpath, print element

Notice: Undefined property: DOMNodeList::$id in D:\wamp\www\xml\index.php on line 15
id:

Notice: Undefined property: DOMNodeList::$name in D:\wamp\www\xml\index.php on line 16
name:

<?php
$xml = new DOMDocument();

$xml->load('test.xml');

$xpath = new DOMXPath($xml);

$query = '/people/person[id="33333"]';

$entries = $xpath->query($query);

echo 'id:'. $entries->id.'<br/>';
echo 'name:'.$entries->name.'<br/>';
?>

xml file sample:

<people>
...
    <person>
        <phone>33333</phone>
        <name>Aadgar</name>
        <last_name>Adas</last_name>
    </person>
...
</people>

Upvotes: 1

Views: 2229

Answers (3)

AliMohsin
AliMohsin

Reputation: 329

try this:

<?php
    $xml = new DOMDocument();

    $xml->load('test.xml');

    $xpath = new DOMXPath($xml);

    $query = '/people/person/phone';

    $entries = $xpath->query($query);

    foreach($entries  as $entry)
    {
       echo $entry;
    }
    ?>

Upvotes: 0

netcoder
netcoder

Reputation: 67695

First, the id node doesn't exists...

$query = '/people/person[id="33333"]';

I think you want:

$query = '/people/person[phone="33333"]';

Then, you must do:

$entries = $xpath->query($query);

foreach ($entries as $entry) {
   echo 'name:'. $entry->getElementsByTagName('name')->item(0)->nodeValue.'<br/>';
   echo 'last_name:'.$entry->getElementsByTagName('last_name')->item(0)->nodeValue.'<br/>';
}

It seems you are mixing up DOM and SimpleXML syntax.

Upvotes: 3

Anush Prem
Anush Prem

Reputation: 1481

you got the xpath wrong. 33333 is phone not id.

try

$query = '/people/person[phone="33333"]';

Also

their is no id

echo 'id:'. $entries->id.'<br/>';
echo 'name:'.$entries->name.'<br/>';

try removeing the id part

Upvotes: 1

Related Questions