在 PHP 中将 CURL XML 响应转换为数组


Convert CURL XML response into Array in PHP

我正在尝试通过 CURL 将 XML 响应转换为 PHP 中的数组。我已经尝试使用以下代码,但没有得到预期的结果数组。

使用simplexml_load_string:

$xml = simplexml_load_string($response);
$json = json_encode($xml);
$arr = json_decode($json,true);
print_r($arr);//giving array () empty 

使用 SimpleXMLElement:

$xml = new SimpleXMLElement($response);
print_r($xml); //giving  SimpleXMLElement Object ( )  empty array 

我的卷发回应:

<?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" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing">
  <soap:Header>
    <OGHeader transactionID="00239870" timeStamp="2009-02-23T01:55:01.4625+05:30" primaryLangID="E" xmlns="http://webservices.micros.com/og/4.3/Core/">
      <Origin entityID="WEST" systemType="ORS" />
      <Destination entityID="OWS" systemType="WEB" />
    </OGHeader>
    <wsa:Action>http://webservices</wsa:Action>
    <wsa:MessageID>urn:uuid:a9a70c23-3d94-4640-9aac-8ac63694733a</wsa:MessageID>
    <wsa:RelatesTo>urn:uuid:eb565d90-b682-45e9-b18d-c03fa7323019</wsa:RelatesTo>
    <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
  </soap:Header>
  <soap:Body>
    <CreateBookingResponse xmlns:r="http://webservices" xmlns:hc="http://webservices/" xmlns:c="http://webservices" xmlns="http://webservices">
      <Result resultStatusFlag="FAIL">
        <c:Text>
          <c:TextElement></c:TextElement>
        </c:Text>
        <c:OperaErrorCode>PRIOR_STAY</c:OperaErrorCode>
      </Result>
    </CreateBookingResponse>
  </soap:Body>
</soap:Envelope>

试试这个:

<?php
$xml = simplexml_load_string($response);
var_dump($xml->asXML());

如您所见,您的 xml 就在那里。

Simplexml 实现了 ArrayIterator,因此您可以使用 foreach 进行迭代或使用任何 simpleXmlElement 方法来浏览它(例如 children()xpath() )。