简体   繁体   中英

simple_xml - Assigning variable to tag - only returning first

I'm trying to create an XML importer to load products from a POS system to an online store.

I'm wanting to go about this by getting the XML export from the POS system, process it and put the values directly into the multiple tables of the database.

The beginning of the code looks like this however I've already ran into a stumbling block.

<?php
    $xml = simplexml_load_file('product.xml');

$ProductName            = $xml->Product->Name;
$ProductDescription     = $xml->Product->Description;
$IsNew = str_replace("false", "0", $xml->Product->IsNew) // Sets False to 0 instead of false

echo $ProductName . "<br />";
echo $ProductDescription . "<br />";
echo $IsNew;
?>

So far I'm just trying to get the data from the XML Tags, put them in variables, and echo them so I see that I'm getting the right results.

This is only returning the details of the first product of the XML file (from over a thousand). I was expecting it to get the Name+Description+IsNew for every product. I'm assuming it needs to be in a while statement, but I can't figure out how to apply this with simple_xml

The XML structure looks like this.

<PRODUCTS>
      <PRODUCT>
              <UPDATETYPE>
              <STYLECODE>
              <NAME>
              <DESCRIPTION>
              ...etc...
              <ITEMS>
                    <ITEM>
                         <CODE>
                         <BARCODE>
                         <SIZE>
                         <PRICE>
                         ...etc...
                    </ITEM>
                    <ITEM>
                    ...etc...
                    </ITEM>
              </ITEMS>
     </PRODUCT>
     <PRODUCT>
     ...etc...
     </PRODUCT>
</PRODUCTS>

You need to traverse Product as an Array:

foreach($xml->Product as $_product){
  echo $_product->Name . "<br/>";
  echo $_product->Description . "<br/>";
  echo $_product->IsNew ? "true" : "false";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM