The problem of converting XML to CSV

I really need help on the problem: I am converting XML to CSV using a PHP script, but I only need to get certain fields in CSV, but not all of them. Is there a way to specify which fields I want to import?

This is the structure of the XML file:

<PRICES> <PRICE> <WIC>HDE0AAFGRBOX</WIC> <DESCRIPTION>some text here</DESCRIPTION> <STOCK>100</STOCK> <MY_PRICE>219.00</MY_PRICE> <IMAGE>some image here</image> <EAN-CODE>some code here</EAN-CODE> </PRICE> </PRICES> 

This is the script I use:

 <? $filexml='stock.xml'; if (file_exists($filexml)) { $xml = simplexml_load_file($filexml); $f = fopen('stock.csv', 'w') foreach($xml->PRICES->PRICE as $price) { fputcsv($f, get_object_vars($price),',','"'); } fclose($f); } ?> 

I only need to get WIC, STOCK and MY_PRICE.

Any help would be greatly appreciated.

Thanks in advance!

+1
source share
1 answer

You need to create an array with these properties and send it to fputcsv() instead of get_object_vars() :

 $filexml='stock.xml'; if (file_exists($filexml)) { $xml = simplexml_load_file($filexml); $f = fopen('stock.csv', 'w'); foreach($xml->PRICES->PRICE as $price) { // Array of just the components you need... $values = array("WIC" => $price->WIC, "STOCK" => $price->STOCK, "MY_PRICE" => $price->MY_PRICE); fputcsv($f, $values,',','"'); } fclose($f); } 

Note. You may need to pass these values ​​as strings. I can’t remember for sure without testing:

 $values = array( "WIC" => (string)$price->WIC, "STOCK" => (string)$price->STOCK, "MY_PRICE" => (string)$price->MY_PRICE ); 
+1
source

All Articles