【问题标题】:PHP parsing empty nodes from XMLPHP从XML解析空节点
【发布时间】:2013-09-19 20:48:25
【问题描述】:

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

如果我预料到了这个问题,我会将每个分配都包装在一个带有错误处理的函数中,但我想知道是否有一个更简单的方法,因为我已经拥有了。

【问题讨论】:

    标签: php xml parsing


    【解决方案1】:

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

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

    此外,正如 Dave 在下面的 cmets 中所说,您还可以使用 property_exists()

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

    【讨论】:

    • 这是 XML 文档中的节点,而不是 PHP 中的节点。在 PHP 中它们是类属性,因此 property_exists() 会更有意义,例如 if (property_exists($node, 'someValue'))
    【解决方案2】:

    你可以做类似的事情

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多