75t*_*one 9 php xml error-handling drupal simplexml
我正在使用SimpleXML.如果我的函数的用户输入无效,我的变量$x
是一个空的SimpleXMLElement对象; 否则,它有一个人口稠密的财产$x->Station
.我想查看是否Station
存在.
private function parse_weather_xml() {
$x = $this->weather_xml;
if(!isset($x->Station)) {
return FALSE;
}
...
}
Run Code Online (Sandbox Code Playgroud)
这样做我想要的,除了它返回一个错误:
警告: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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
这几乎完全相同:
警告: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();
...
}
Run Code Online (Sandbox Code Playgroud)
它返回自己的HTML页面:
处理异常时抛出的其他未捕获异常.
原版的
ErrorException:property_exists():在crazy_error()中不再存在节点(vvdtn.inc的第183行).
额外
ErrorException:stat():stat_seror /files/less/512d40532e2976.99442935在crazy_error()中失败(/includes/stream_wrappers.inc的第689行).
所以现在我歇斯底里地笑着放弃了.如何在不以某种形式出现此错误的情况下检查SimpleXML对象的属性是否存在?
您想检查您是否simplexml
包含某个节点吗?--> 数一数!
编辑:节点不存在时出现错误 --> 尝试 xpath:
if ($xml->xpath("//station")->Count()==0) echo "no station!";
Run Code Online (Sandbox Code Playgroud)
如果没有站节点,将抛出错误:
说$xml
是你的simplexml
并且station
位于顶层:
if ($xml->station->Count()==0) echo "no station!";
Run Code Online (Sandbox Code Playgroud)
比如说,如果“station”是 的子项<something>
,那么您当然会去...
... $xml->something->station->Count();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4057 次 |
最近记录: |