如何将XML响应从curl转换为json


$response = curl_exec($ch);
curl_close($ch);
dd($response);

它的类型为响应字符串。

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns3:GetProductListResponse xmlns:ns3="http://xxx1">
<result>
<status>success</status>
</result>
<products>
<product>
<currencyAmount>900.00</currencyAmount>
<currencyType>1</currencyType>
<displayPrice>900.00</displayPrice>
<isDomestic>false</isDomestic>
<id>557830715</id>
<price>900.00</price>
<productSellerCode>TSRT7777</productSellerCode>
<approvalStatus>6</approvalStatus>
...

为了将这些数据转换为xml,我使用了simplexml_load_string((

$response = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($response);
dd($xml);

输出是这样的。

^ SimpleXMLElement {#435}

我正在尝试访问其中的数据并尝试此操作。

$status = (string)$xml->result->status;
dd($status);

退货:

^ ""

我尝试使用simplexml_load_file((,但没有得到任何结果。我的主要目标是将这些数据作为json获取,但我无法做到这一点,因为我无法读取值。任何帮助都会很棒。提前谢谢。

在@Jacob Mulquin的建议之后,我使用了:

if ($xml === false) {
dump("b");
foreach (libxml_get_errors() as $error) {
dump($error->message);
}
dd("a");
} else {
dd("c");
}

返回:";c";

由于各种原因,您的示例xml格式不正确,但假设实际的$response是一个格式正确的xml字符串,以下内容应该可以满足您的需要:

#first you need to deal with namespaces
$xml->registerXPathNamespace("ns3", "http://xxx1");
#then use xpath to select your target element
$status = $xml->xpath('//ns3:GetProductListResponse//status')[0];
echo $status;

输出应为

success

最新更新