I have been experimenting with SimplXML to parse out some specific information from a very large XML document to create a new simplified one. I am working with products and the products have variations (like size for instance) that I am trying to build into the array. Some testing is showing that the variation loop is adding the last results onto the next. For instance:
First loop shows this, which is correct for the first product which has 2 variations.
["variations"]=> array(2) { [0]=> array(1) { ["sku"]=> object(SimpleXMLElement)#19 (1) { [0]=> string(8) "00090011" } } [1]=> array(1) { ["sku"]=> object(SimpleXMLElement)#19 (1) { [0]=> string(8) "00090012" } } }
Now the second product in the loop ends up containing the last loops results and adds it before it's own results.
["variations"]=> array(4) { [0]=> array(1) { ["sku"]=> object(SimpleXMLElement)#19 (1) { [0]=> string(8) "00090011" } } [1]=> array(1) { ["sku"]=> object(SimpleXMLElement)#19 (1) { [0]=> string(8) "00090012" } } [3]=> array(1) { ["sku"]=> object(SimpleXMLElement)#19 (1) { [0]=> string(8) "00090013" } } [4]=> array(1) { ["sku"]=> object(SimpleXMLElement)#19 (1) { [0]=> string(8) "00090014" } } }
As you can imagine, this ends up resulting in memory errors and a giant new XML file being created at the end since it's prepends everything before it. Here is my PHP code doing the loop.
foreach($data as $element) { if ($element->Dir_Name == "Fly Fishing"){ //assign element nodes to variables $name = $element->PF_Name; $id = $element->PF_ID; $description = $element->PF_Description; $brand = $element->Manufacturer_Brand; $image = $element->ImageURL; $category1 = $element->Dir_Name; $category2 = $element->Group_Name; $category3 = $element->Cat_Name; //pull in variations $item_data = $element->Item; foreach($item_data->Sku as $variation){ $optionName = $variation->Sku_Name; $price = $variation->Regular_Price; $sku = $variation->Item_Code; $variation_array[] = array( "optionName" => $optionName, "price" => $price, "sku" => $sku ); } $products_array[] = array( "name" => $name, "description" => $description, "brand" => $brand, "image" => $image, "category1" => $category1, "category2" => $category2, "category3" => $category3, "variations" => $variation_array ); } }
I read something about using unset() to try and correct this but it didn't work out. Any help is much appreciated.
No comments:
Post a Comment