0

i have put this code in i get all the right products_id but all the products_model are the same number

 foreach($xml->xpath('//PRODUCT/@ITEM') as $productitemid){
 foreach($xml->CREATED->CATEGORY->PRODUCT as $product)

 mysql_query("INSERT INTO products (products_id,products_model) VALUES ('$productitemid','$product->MODEL')");

} 
4
  • Can we see how the XML is formatted? Thanks. Commented Feb 22, 2013 at 15:11
  • <?xml version="1.0" encoding="iso-8859-1"?> <STOREITEMS> <CREATED value="Fri Feb 22 1:01:02 GMT 2013"> <CATEGORY id="442" name=" > test"> <PRODUCT ITEM="12796"> <NAME>Furry test</NAME> <MODEL>bb2018</MODEL> <PRICE>2.28</PRICE> <RRP>3.99</RRP> <THUMB>bb2018s.jpg</THUMB> <IMAGE>bb2018.jpg</IMAGE> <DESCRIPTION> Commented Feb 22, 2013 at 15:21
  • It would be even more helpful if you would edit your initial post, since you can't format code in comments... Commented Feb 22, 2013 at 15:23
  • these are at the end file </DESCRIPTION> </PRODUCT> </CATEGORY> </CREATED> </STOREITEMS> Commented Feb 22, 2013 at 15:23

1 Answer 1

1

If you have multiple 'product' items in your input file, then you need to iterate through them. You 'foreach' needs to look look something like this:

foreach($xml->CREATED->CATEGORY->PRODUCT as $product)
    mysql_query("INSERT INTO products (products_model) VALUES ('$product->model')")

Notice that the problem is that your code $xml->CREATED->CATEGORY->PRODUCT->MODEL means "get me the 'MODEL' elements from the first 'PRODUCT' element. So that's why you only get one item.

Hope this helps.

Sign up to request clarification or add additional context in comments.

2 Comments

i have put in code like you now i get all the right products_id but all the products_model are the same number foreach($xml->xpath('//PRODUCT/@ITEM') as $productitemid){ foreach($xml->CREATED->CATEGORY->PRODUCT as $product) mysql_query("INSERT INTO products (products_id,products_model) VALUES ('$productitemid','$product->MODEL')"); }
You need to think about what exactly is being looped over in each of your foreach statements - your latest code has an outer foreach looking at $xml->xpath('//PRODUCT/@ITEM') and an inner loop looking at $xml->CREATED->CATEGORY->PRODUCT, but there's nothing to relate these two, so you'll just get every possible combination of those two loops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.