2015-10-14 71 views
0

我想將XML響應轉換爲JSON數據,但響應比我想要的要複雜。PHP XML到JSON

我的PHP文件:

... 
    $client = new SoapClient($wsdl_path, array('login' => $login, 'password' => $password)); 

    $params = array('ProductId' => "C0041000"); 
    $result = $client->__soapCall('GetProduct', array('parameters' => $params));   
    $xml = simplexml_load_string($result->GetProductResult->any); 

    echo json_encode($xml); 
    var_dump($xml); 

我的瀏覽器響應:

{"DocumentInfo":{"DocType":"PRODUCT","DocVersion":"2.3"},"Header":{"LangId":"RO"},"Products":{"Product":{"ProductId":"C0041000","PartNumber":"KS-MC-CC12","ClientProductId":{},"ProductName":{},"MajorGroup":"MOD","MinorGroup":"VDC","HierarchyId":"36491","ProducerId":"MODE_COM","Price":"413.17","CurrencyId":"RON","Available":"+","RecyclingFee":"0.84","CopyrightFee":"0","VatRate":"0.24","WarrantyId":"A ","AttribGroupId":"481","BarCodes":{"BarCodeInfo":{"BarCodeType":"EAN13","BarCode":"5901885242651"}},"VatCode":"24%","AvailableExternal":"-"}}} 

object(SimpleXMLElement)[4] 
    public 'DocumentInfo' => 
    object(SimpleXMLElement)[7] 
     public 'DocType' => string 'PRODUCT' (length=7) 
     public 'DocVersion' => string '2.3' (length=3) 
    public 'Header' => 
    object(SimpleXMLElement)[8] 
     public 'LangId' => string 'RO' (length=2) 
    public 'Products' => 
    object(SimpleXMLElement)[9] 
     public 'Product' => 
     object(SimpleXMLElement)[12] 
      public 'ProductId' => string 'C0041000' (length=8) 
      public 'PartNumber' => string 'KS-MC-CC12' (length=10) 
      public 'ClientProductId' => 
      object(SimpleXMLElement)[10] 
       ... 
      public 'ProductName' => 
      object(SimpleXMLElement)[11] 
       ... 
      public 'MajorGroup' => string 'MOD' (length=3) 
      public 'MinorGroup' => string 'VDC' (length=3) 
      public 'HierarchyId' => string '36491' (length=5) 
      public 'ProducerId' => string 'MODE_COM' (length=8) 
      public 'Price' => string '413.17' (length=6) 
      public 'CurrencyId' => string 'RON' (length=3) 
      public 'Available' => string '+' (length=1) 
      public 'RecyclingFee' => string '0.84' (length=4) 
      public 'CopyrightFee' => string '0' (length=1) 
      public 'VatRate' => string '0.24' (length=4) 
      public 'WarrantyId' => string 'A ' (length=4) 
      public 'AttribGroupId' => string '481' (length=3) 
      public 'BarCodes' => 
      object(SimpleXMLElement)[6] 
       ... 
      public 'VatCode' => string '24%' (length=3) 
      public 'AvailableExternal' => string '-' (length=1) 

我從這個JSON從類似產品編號和PriceId領域產品領域唯一的數據所需要的,但我不能這樣做那。

我與努力:

json_encode($xml->Products->Product->Price); 

,但不工作。

在此先感謝您的解決方案!

回答

1

您可以創建一個數組,並投它作爲一個對象,僅設置你需要的屬性:

echo json_encode((object) array('productId' => $xml->Products->Product->ProductId, 'price' => $xml->Products->Product->Price)); 
+0

確定。它正在工作!現在在瀏覽器中我有'''{「productId」:{「0」:「C0041000」},「price」:{「0」:「413.17」}}'''。如果我只想回顯價格字段的值? –

+1

只是單一的價值?只是回聲:)回聲$ xml->產品 - >產品 - >價格;' – taxicala