PHP从XML解析空节点

时间:2013-09-19 20:48:26

标签: php xml parsing

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] || ""

如果我已经预料到了这个问题,我会把每个作业都包装在一个有错误处理的函数中,但是我想知道是否有一个更简单的方法给出我已经拥有的东西。

2 个答案:

答案 0 :(得分:0)

我使用isset()来确保节点存在:

if(isset($node->SomeValue)) {
    $arr['item'] = $node->SomeValue;
} else {
    $arr['item'] = ''
}

另外,正如Dave在下面的评论中指出的那样,您也可以使用property_exists()

if (property_exists($node, 'someValue')) {
    $arr['item'] = $node->SomeValue;
} else {
    $arr['item'] = '';
}

答案 1 :(得分:0)

你可以做一些像

这样的事情
$reportItems['propertyBaths'] = ''.$report187->PropertyProfile->PropertyCharacteristics->Baths[0];

会自动将xml子项的结果转换为字符串,如果不存在则返回emptystring。正是你想要的而不是测试