在没有“节点不再存在”警告的情况下检查属性是否存在

时间:2013-02-26 23:27:19

标签: php xml drupal error-handling simplexml

我正在使用SimpleXML。如果我的函数的用户输入无效,我的变量$x是一个空的SimpleXMLElement对象;否则,它具有填充的属性$x->Station。我想查看Station是否存在。

private function parse_weather_xml() {
    $x = $this->weather_xml; 
    if(!isset($x->Station)) {
        return FALSE;
    }

    ...
}

这样做我想要的,除了它返回错误:

  

警告:WeatherData :: parse_weather_xml():WeatherData-> parse_weather_xml()中不再存在节点(vvdtn.inc的第183行)。

好的,isset()已经结束了。我们试试这个:

private function parse_weather_xml() {
    $x = $this->weather_xml; 
    if(!property_exists($x, 'Station')) {
        return FALSE;
    }

    ...
}

这几乎完全相同:

  

警告:property_exists():WeatherData-> parse_weather_xml()中不再存在节点(vvdtn.inc的第183行)

好吧,好吧,我会把它变成一个例外而忽视它。我以前从未这样做过,我不确定我做得对,但我会尝试一下:

function crazy_error($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}

...

    private function parse_weather_xml() {
        set_error_handler('crazy_error');
        $x = $this->weather_xml; 
        if(!property_exists($x, 'Station')) {
            return FALSE;
        }
        restore_error_handler();

        ...
    }

返回自己的HTML页面:

  

处理异常时抛出的其他未捕获异常。

     

原始

     

ErrorException:property_exists():在crazy_error()中不再存在节点(vvdtn.inc的第183行)。

     

其他

     

ErrorException:stat():在crazy_error()中的/sites/default/files/less/512d40532e2976.99442935失败(/includes/stream_wrappers.inc的第689行)。

     

所以现在我歇斯底里地笑着放弃了。如何在不以某种形式出现此错误的情况下检查SimpleXML对象的属性是否存在?

4 个答案:

答案 0 :(得分:1)

您想检查simplexml是否包含某个节点吗? - >算他们!

编辑:节点不存在时的错误 - >试试xpath:

if ($xml->xpath("//station")->Count()==0) echo "no station!";

如果没有station-node:

将抛出错误

$xmlsimplexmlstation位于顶层:

 if ($xml->station->Count()==0) echo "no station!";

如果'站'是一个<something>的孩子,你当然会去...

... $xml->something->station->Count();

答案 1 :(得分:0)

if (!$x || !$x->Station) {
    return false;
}

重要的是 - !$x - 你需要检查这个xml对象是否为空。如果确实如此,那么在任何尝试解决$x->Station时都会出现此错误。

答案 2 :(得分:0)

首先检查您是否错误地尝试访问属性而未检查您要检查的代码位之前(有时错误消息与行号不准确)。

然后我使用了isset,它运行正常:

 if(isset($xml->element))
 {
      // $xml has element 
 }

答案 3 :(得分:0)

您是否尝试过property_exists()

private function parse_weather_xml() {
  $x = $this->weather_xml; 
  if(!property_exists($x,"Station")) {
    return FALSE;
  }
...
}

并考虑到这一点:

As opposed with isset(), property_exists() returns TRUE even if the property has the value NULL.