Mr Talha
Mr Talha

Reputation: 825

I cannot get data from xml file

Please read carefully and I appreciate for your help and answers.

My code is getting data from xml and show but its works just on my categories.xml not on my products.xml.

This is my categories.xml structure:

 <?xml version="1.0"?>
<categories>
<category>
<categories_name>name</categories_name>
<sort_order>order number</sort_order>
</category>
<category>
<categories_name>name</categories_name>
<sort_order>order number</sort_order>
 </category>
</categories>

and the code I used

<?php
$xml=simplexml_load_file("categories.xml") or die("Error: Cannot create object");
foreach ($xml->children() as $category): ?>
    <div class="product">
            <img src="<?= $category->categories_name; ?>"><br>
            <?= $category->sort_order; ?>
    </div>
<?php endforeach; ?>

and its working perfectly.

But when I tried this code on my products.xml its showing blank. Here is my products.xml:

<TABLE-RECORDS>
<EXPORT-RECORDS>
<PRODUCT>
  <PRODUCTS_NAME>name </PRODUCTS_NAME>
  <PRODUCTS_DESCRIPTION>details</PRODUCTS_DESCRIPTION>
  <PRODUCTS_IMAGE>number</PRODUCTS_IMAGE>
  <PRODUCTS_PRICE>$</PRODUCTS_PRICE>
</PRODUCT>
<PRODUCT>
  <PRODUCTS_NAME>name </PRODUCTS_NAME>
  <PRODUCTS_DESCRIPTION>details</PRODUCTS_DESCRIPTION>
  <PRODUCTS_IMAGE>number</PRODUCTS_IMAGE>
  <PRODUCTS_PRICE>$</PRODUCTS_PRICE>
</PRODUCT>
</EXPORT-RECORDS>
</TABLE-RECORDS>

and here is the php code for fetching:

<?php $xml=simplexml_load_file("products.xml") or die("Error: Cannot create object"); 
foreach ($xml->children() as $product): ?>
    <div class="product">
            <?= $product->PRODUCTS_NAME; ?>
    </div>

I think I'm getting error on TABLE-RECORDS. I checked many times but I didn't fetch any thing ... it shows me a blank page.

Upvotes: 0

Views: 1078

Answers (1)

tomtomtom
tomtomtom

Reputation: 899

I think you forget to find the sub child, can you try

<?php $xml=simplexml_load_file("products.xml") or die("Error: Cannot create object"); 
foreach ($xml->children()->children() as $product): ?>
  <div class="product">
    <?= $product->PRODUCTS_NAME; ?>
  </div>
}

Upvotes: 1

Related Questions