2012-02-11 85 views
1

我真的需要一些問題的幫助:我使用PHP腳本將XML轉換爲CSV,但我只需要獲取CSV中的某些字段,而不是所有字段。有什麼方法可以指定我想要導入的字段嗎?XML到CSV轉換問題

這是XML文件的結構:

<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> 

這是我使用的腳本:

<? 
$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); 
} 
?> 

我只需要得到WIC,股票和MY_PRICE。

任何幫助將不勝感激。

在此先感謝!

回答

1

你只需要創建具有這些屬性的數組,並將其發送到fputcsv(),而不是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); 
} 

注:可能有必要投這些值作爲字符串。我不記得一定沒有測試:

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

謝謝,它完美的作品! – alexius 2012-02-11 17:08:36