2010-09-05 52 views
7

存在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更好嗎?

回答

27

聽起來像一個簡單的isset()解決了這個問題。

<?php 
$s = new SimpleXMLElement('<foo version="1"> 
    <weather section="0" /> 
    <problem_cause data="" /> 
</foo>'); 
// var_dump($s) produces the same output as in the question, except for the object id numbers. 
echo isset($s->problem_cause) ? '+' : '-'; 

$s = new SimpleXMLElement('<foo version="1"> 
    <weather section="0" /> 
</foo>'); 
echo isset($s->problem_cause) ? '+' : '-'; 

打印+-沒有任何錯誤/警告消息。

+0

哦,謝謝。這是一個非常簡單的解決方案。 – reggie 2010-09-07 08:42:09

+0

最好使用'empty()'而不是'isset()'。如果訪問對象的子對象不存在,它將創建它,所以SimpleXMLElement將返回一個空元素,並且'isset()'將返回true。 – 2017-03-26 13:49:31

+0

@ MugomaJ.Okomba'empty()'返回true,即使節點存在但沒有內容 – CITBL 2017-04-18 11:46:44

2

使用您發佈的代碼,本示例應該可以在任意深度查找problem_cause節點。

function xml_child_exists($xml, $childpath) 
{ 
    $result = $xml->xpath($childpath); 
    return (bool) (count($result)); 
} 

if(xml_child_exists($xml, '//problem_cause')) 
{ 
    echo 'found'; 
} 
else 
{ 
    echo 'not found'; 
} 
1

試試這個:

function xml_child_exists($xml, $childpath) 
{ 
    $result = $xml->xpath($childpath); 
    if(!empty($result)) 
{ 
    echo 'the node is available'; 
} 
else 
{ 
    echo 'the node is not available'; 
} 
} 

我希望這將幫助你..