我有一個測試文件,我試圖用SimpleXML的xpath方法分析一個xml字符串。xml xpath不返回節點值
當我嘗試直接使用xpath訪問節點值時,我得到空輸出,但是當我使用xpath抓取元素並通過它們循環時,它工作正常。
當我看文檔時,似乎我的語法應該工作。有什麼我失蹤?
<?php
$xmlstring = '<?xml version="1.0" encoding="iso-8859-1"?>
<users>
<user>
<firstname>Sheila</firstname>
<surname>Green</surname>
<address>2 Good St</address>
<city>Campbelltown</city>
<country>Australia</country>
<contact>
<phone type="mobile">1234 1234</phone>
<url>http://example.com</url>
<email>[email protected]</email>
</contact>
</user>
<user>
<firstname>Bruce</firstname>
<surname>Smith</surname>
<address>1 Yakka St</address>
<city>Meekatharra</city>
<country>Australia</country>
<contact>
<phone type="landline">4444 4444</phone>
<url>http://yakka.example.com</url>
<email>[email protected]</email>
</contact>
</user>
</users>';
// Start parsing
if(!$xml = simplexml_load_string($xmlstring)){
echo "Error loading string ";
} else {
echo "<pre>";
// Print all firstname values directly from xpath
// This outputs the elements, but the values are blank
print_r($xml->xpath("https://stackoverflow.com/users/user/firstname"));
// Set a variable with all of the user elements and then loop through and print firstname values
// This DOES output the values
$users = $xml->xpath("https://stackoverflow.com/users/user");
foreach($users as $user){
echo $user->firstname;
}
// Find all firstname values by tag
// This does not output the values
print_r($xml->xpath("//firstname"));
echo "</pre>";
}
位混淆。結果將返回所有三個查詢。你只是無法獲取數據嗎? – rjdown 2014-10-26 18:55:39