Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/235.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP解析XML中的空节点_Php_Xml_Parsing - Fatal编程技术网

PHP解析XML中的空节点

PHP解析XML中的空节点,php,xml,parsing,Php,Xml,Parsing,这里是PHP新手。我编写了一个脚本,用于解析从API获取的XML报告。在某些报告中,某些节点不存在,因此当我尝试从节点获取值时,会收到错误通知:尝试获取非对象的属性。我不知道如何处理这个问题,因为我有数百行,如下面所示,它们将节点值分配给关联数组 $reportItems['propertyBaths'] = $report187->PropertyProfile->PropertyCharacteristics->Baths[0]; $reportItems['propert

这里是PHP新手。我编写了一个脚本,用于解析从API获取的XML报告。在某些报告中,某些节点不存在,因此当我尝试从节点获取值时,会收到错误通知:尝试获取非对象的属性。我不知道如何处理这个问题,因为我有数百行,如下面所示,它们将节点值分配给关联数组

$reportItems['propertyBaths'] = $report187->PropertyProfile->PropertyCharacteristics->Baths[0];
$reportItems['propertyRooms'] = $report187->PropertyProfile->PropertyCharacteristics->TotalRooms[0];
$reportItems['propertyYear'] = $report187->PropertyProfile->PropertyCharacteristics->YearBuilt[0];
在节点不存在的情况下,我希望分配一个空字符串。我想知道是否有一种简单的方法可以做到这一点,而不需要彻底改变我已经写过的内容,比如:

$reportItems['propertyBaths'] = $report187->PropertyProfile->PropertyCharacteristics->Baths[0] || ""
如果我预料到了这个问题,我会将每个赋值封装在一个带有错误处理的函数中,但是我想知道,如果我已经有了这样一个函数,是否有更简单的方法

我将使用以确保节点存在:

if(isset($node->SomeValue)) {
    $arr['item'] = $node->SomeValue;
} else {
    $arr['item'] = ''
}
此外,正如Dave在下面的评论中指出的,您还可以使用:


你可以这样做

$reportItems['propertyBaths'] = ''.$report187->PropertyProfile->PropertyCharacteristics->Baths[0];

它将自动将xml子级的结果转换为字符串,如果不存在,则返回emptystring。这正是您想要的,而无需测试

,这是XML文档中的节点,而不是PHP中的节点。在PHP中,它们是类属性,因此属性_exists更有意义,比如如果属性_exists$node,'someValue'
$reportItems['propertyBaths'] = ''.$report187->PropertyProfile->PropertyCharacteristics->Baths[0];