PHP Fatal error: Call to a member function item() on a non-object
<p>I have an XML file and want to insert the data into a database with php.
A sample of XML file is:         </p>

<pre><code>&lt;shops&gt;
 &lt;shop&gt;
   &lt;code&gt;HM&lt;/code&gt;
   &lt;name&gt;Beauty&lt;/name&gt;
   &lt;address&gt;
     &lt;address_name&gt;George St &lt;/address_name&gt;
     &lt;city&gt;New York&lt;/city&gt;
   &lt;/address&gt;
 &lt;/shop&gt;
&lt;/shops&gt;
</code></pre>

<p>I want to insert the values of code,name,address_name and city into my database with php.</p>

<p>My php code is:</p>

<pre><code>$xmlDoc = new DOMDocument();
$xmlDoc-&gt;load("shops.xml");

$xmlObject = $xmlDoc-&gt;getElementsByTagName('shop');
$itemCount = $xmlObject-&gt;length;
for ($i=0; $i &lt; $itemCount; $i++) {
  $name = $xmlObject-&gt;item($i)-&gt;getElementsByTagName('name')-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
  $code = $xmlObject-&gt;item($i)-&gt;getElementsByTagName('code')-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
  $sql  = "INSERT INTO `shop` (name,code) VALUES ('$name', '$code')";
  mysql_query($sql);
} 

$xmlObject_n = $xmlDoc-&gt;getElementsByTagName('address');
for ($i=0; $i &lt; $itemCount; $i++) {
  $address_n = $xmlObject_n-&gt;item($i)-&gt;getElementsByTagName('address_name')-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
  $city      = $xmlObject_n-&gt;item($i)-&gt;getElementsByTagName('city')-&gt;item(0)-&gt;childNodes-&gt;item(0)-&gt;nodeValue;
  $sql_n     = "INSERT INTO `place` (address,city) VALUES ('$address_n', '$city')";
  mysql_query($sql_n);
}
</code></pre>

<p>While the data for the table shop in the first for loop are loaded properly, I get the following error for the second loop:</p>

<blockquote>
  <p>PHP Fatal error:  Call to a member function item() on a non-object</p>
</blockquote>

<p>Does anyone have any idea how to fix this in order to get the values for the element address? </p>

<p>Thanks a lot</p>