2012-02-21 119 views
2

我需要以下方面的幫助:我編寫了一個腳本來從web服務獲取響應,然後將其保存在我的服務器上的XML文件中。這是XML文件的結構:將XML SOAP響應轉換爲CSV

<xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<soap:Body> 
<GetCatalogResponse xmlns="http://tempuri.org/"> 
<GetCatalogResult> 
<Products> 
<Product> 
<Code>1234</Code> 
<Name>product name</Name> 
<Category>some category</Category> 
<Manufacturer>manufacturer</Manufacturer> 
<Price>100</Price> 
<Stock>1</Stock> 
</Product> 
</Products> 
</GetCatalogResult> 
</GetCatalogResponse> 
</soap:Body> 
</soap:Envelope> 

我使用這個腳本將XML文件轉換成CSV:

$filexml='filename.xml'; 
if (file_exists($filexml)) { 
$xml = simplexml_load_file($filexml); 
$f = fopen('filename.csv', 'w'); 

// I only need the CSV to contain two columns, the product code and the corresponding price 

foreach($xml->Products->Product as $Product) { 
$values = array("Code" => $Product->Code, "Price" => $Product->Price); 
fputcsv($f, $values,',','"'); 
} 
fclose($f); 
} 

的問題是,有在CSV文件中沒有輸出,我的猜測是命名空間存在問題,但我無法解決它,即使我已經閱讀了此處給出的類似問題的所有解決方案。

任何幫助將不勝感激。

回答

2

問題是在這裏:

$xml->Products->Product 

看看你的XML結構,它是這樣的:

<soap:Body> 
    <GetCatalogResponse xmlns="http://tempuri.org/"> 
    <GetCatalogResult> 
     <Products> 
     <Product> 

Products一些節點裏面,你不能直接訪問它。

+0

我知道,我不知道如何訪問該特定的節點。有關如何解決問題的任何想法?謝謝! – alexius 2012-02-21 16:43:51

+1

首先將「」轉換爲「第二次使用」$ xml-> soap :Envelope-> soap:Body-> GetCatalogResponse-> GetCatalogResult-> Products-> Product「代替」$ xml-> Products-> Product「。 – Ocelot 2012-02-21 16:47:48

+0

我已經試過這個選項,但是我得到一個PHP錯誤:PHP解析錯誤:語法錯誤,第9行中出現意外的':',它是$ xml-> soap:Envelope-> soap:Body-> GetCatalogResponse-> GetCatalogResult-> Products-> Product – alexius 2012-02-21 16:56:00