XML到MySQL检查XML字段是否为空

时间:2017-06-06 20:18:51

标签: php mysql xml

我通过从XML文件读取数据并使用PHP将数据推送到我的MySQL表来学习XML,MySQL和PHP,我遇到的问题是当XML字段为空时,它是返回错误:Notice: Trying to get property of non-object in C:\xampp\htdocs\Website\update-products.php on line 177

如何检查每个对象的字段是否为空?

XML代码

<?xml version="1.0"?>
<books>
  <book isbn="978-1594489501">
    <title></title>
    <author>Khaled Hosseini</author>
    <publisher>Riverhead Hardcover</publisher>
    <amazon_price></amazon_price>
  </book>
  <book isbn="978-1594489587">
    <title>The Brief Wondrous Life of Oscar Wao</title>
    <author>Junot Diaz</author>
    <publisher></publisher>
    <amazon_price>14.97</amazon_price>
  </book>
  <book isbn="978-0545010221">
    <title>Harry Potter and the Deathly Hallows</title>
    <author>J. K. Rowling</author>
    <publisher>Arthur A. Levine Books</publisher>
    <amazon_price>19.24</amazon_price>
  </book>
</books>```

PHP代码的一部分

$publisher = $xmlObject->item($i)->getElementsByTagName('publisher')->item(0)->childNodes->item(0)->nodeValue;

1 个答案:

答案 0 :(得分:1)

如果不看第177行的代码,很难说清楚。 话虽如此,在操作它们之前,您需要检查是否存在可能缺失的节点。

if(isset($document->node->child)){
   doStuff($document->node->child);
}

这样,您可以跳过文档中缺少的节点而不会出现错误。