Reputation: 73
I really need some help on an issue: I'm converting an XML to CSV using a PHP script, but I only need to get certain fields in the CSV, not all of them. Is there any way to specify which fields I want to import?
This is the XML file structure:
<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 will be greatly appreciated.
Thanks in advance!
Upvotes: 1
Views: 1345
Reputation: 270767
You only need to create an array with those 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: It may be necessary to cast these values as strings. I can't remember for certain without testing:
$values = array(
"WIC" => (string)$price->WIC,
"STOCK" => (string)$price->STOCK,
"MY_PRICE" => (string)$price->MY_PRICE
);
Upvotes: 1