2017-06-06 169 views
0

通过读取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 177XML到MySQL检查XML字段是否为空

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

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

很难说清楚没有看到周围行代码177 虽这么说,你需要在对它们进行操作之前检查是否存在潜在的缺失节点。

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

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

+0

嘿,对不起,我只是刚到电脑。 对不起,[这里有一个链接](https://pastebin.com/1grJRZkr)到一个包含更完整代码的pastebin。 所以我试了一行,但之后,我得到一个错误,说它是一个未定义的变量。 下面是我如何编写代码: 'if(isset($ document-> node-> child)){{{0}} {product_code = $ xmlObject-> item($ i) - > getElementsByTagName('product_code') - >项(0) - > childNodes->项(0) - >的nodeValue; }' – ConduciveMammal