12

私はこの simplexml 結果オブジェクトを持っています:

 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 に変換した方がよいでしょうか?

4

4 に答える 4

37

単純な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)  ? '+' : '-';

+-エラー/警告メッセージなしで印刷されます。

于 2010-09-05T14:04:57.227 に答える
3

あなたが投稿したコードを使用すると、この例では、任意の深さで 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';
}
于 2010-09-05T15:12:54.007 に答える
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';
     }
 }

これがあなたに役立つことを願っています..

于 2012-10-20T11:32:26.623 に答える
0

置く*/problem_cause

于 2010-09-05T13:15:00.550 に答える