2010-12-20 176 views
1
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文件樣本:XML +的XPath,打印元素

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

'$查詢= '/人/人[手機= 「33333」]';' – khachik 2010-12-20 18:37:02

回答

3

首先,id節點不存在...

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

我想你想:

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

然後,你必須做到:

$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/>'; 
} 

看來你在混合使用DOMSimpleXML語法。

1

你得到了XPath的錯誤。 33333是手機沒有身份證。

嘗試

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

而且

他們是沒有id

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

嘗試removeing ID部

0

試試這個:

<?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; 
    } 
    ?> 
+0

這將打印3333 – AliMohsin 2012-10-20 07:14:02