PHP XML to JSON


PHP XML to JSON

我想将XML响应转换为JSON数据,但是响应比我想要的更复杂。

My PHP file:

...
    $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只从产品区域的数据,如ProductId和PriceId字段,但我不能这样做。

我正在尝试:

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

但不工作。

提前感谢任何解决方案!

您可以创建一个数组并将其强制转换为对象,只设置您需要的属性:

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