存在XML節點我有這個SimpleXML的結果對象:檢查是否在PHP
object(SimpleXMLElement)#207 (2) {
["@attributes"]=>
array(1) {
["version"]=>
string(1) "1"
}
["weather"]=>
object(SimpleXMLElement)#206 (2) {
["@attributes"]=>
array(1) {
["section"]=>
string(1) "0"
}
["problem_cause"]=>
object(SimpleXMLElement)#94 (1) {
["@attributes"]=>
array(1) {
["data"]=>
string(0) ""
}
}
}
}
我需要檢查,如果節點「problem_cause」的存在。即使它是空的,結果也是一個錯誤。 在PHP手冊中,我發現這個PHP代碼,我修改我的需求:
function xml_child_exists($xml, $childpath)
{
$result = $xml->xpath($childpath);
if (count($result)) {
return true;
} else {
return false;
}
}
if(xml_child_exists($xml, 'THE_PATH')) //error
{
return false;
}
return $xml;
我不知道該怎麼落實到位XPath查詢「THE_PATH」的檢查,如果節點存在。 或者將simplexml對象轉換爲dom更好嗎?
哦,謝謝。這是一個非常簡單的解決方案。 – reggie 2010-09-07 08:42:09
最好使用'empty()'而不是'isset()'。如果訪問對象的子對象不存在,它將創建它,所以SimpleXMLElement將返回一個空元素,並且'isset()'將返回true。 – 2017-03-26 13:49:31
@ MugomaJ.Okomba'empty()'返回true,即使節點存在但沒有內容 – CITBL 2017-04-18 11:46:44