10

我正在使用 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(): stat failed for /sites/default/files/less/512d40532e2976.99442935 in crazy_error()(/includes/stream_wrappers.inc 的第 689 行)。


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

4

4 回答 4

1

你想检查你是否simplexml包含某个节点吗?--> 数一数!

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

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

如果没有站节点将抛出错误:

Say $xmlis your simplexmland stationis on the top level:

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

如果“站”是,比如说,一个孩子<something>,你当然会去......

... $xml->something->station->Count();
于 2013-02-26T23:33:58.057 回答
0

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

然后我使用了isset,它工作正常:

 if(isset($xml->element))
 {
      // $xml has element 
 }
于 2017-08-30T21:56:40.983 回答
0
if (!$x || !$x->Station) {
    return false;
}

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

于 2017-03-01T05:18:59.410 回答
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.
于 2017-09-02T08:11:46.940 回答