ConduciveMammal
ConduciveMammal

Reputation: 483

XML to MySQL check if XML field is empty

I'm learning a little about XML, MySQL and PHP by reading data from and XML file and using PHP to push that data to my MySQL table, the problem I'm running into is when an XML field is empty, it's returning an error: Notice: Trying to get property of non-object in C:\xampp\htdocs\Website\update-products.php on line 177.

How can I do a check to see if the field is empty for each object?

XML Code

<?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>```

Part of PHP Code

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

Upvotes: 0

Views: 287

Answers (1)

Royall Spence
Royall Spence

Reputation: 240

It's hard to say exactly without seeing the code around line 177. With that said, you'll need to check for the existence of potentially missing nodes before operating on them.

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

This way you can skip missing nodes in the document without hitting an error.

Upvotes: 1

Related Questions