Guzzle PHP:解析从 WebService 返回的 XML
Guzzle PHP: Parse XML returned from WebService
我正在使用 Guzzle 调用 USPS 地址验证服务,并在响应中得到 XML。然后我使用以下方法从 XML 获取正文:
$body = $response->getBody();
产生以下内容:
<AddressValidateResponse>
<Address ID="0">
<Error>
<Number>-2147219400</Number>
<Source>clsAMS</Source>
<Description>Invalid City. </Description>
<HelpFile/>
<HelpContext/>
</Error>
</Address>
</AddressValidateResponse>
我需要对其进行解析以获取说明。
$body 当前是一个对象。我尝试将其转换为数组,但得到以下结果,这不是我想要的:
array (
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'stream' => NULL,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'size' => NULL,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'seekable' => true,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'readable' => true,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'writable' => true,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'uri' => 'php://temp',
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'customMetadata' =>
array (
),
)
有谁知道如何解析 $body 以获得描述节点?
感谢您的指导!
在 PHP 中使用 XML 处理简单任务的最简单方法可能是通过 SimpleXML:
$xml = simplexml_load_string($body);
// Or if you're dealing with a Guzzle Response, you can even do
// $xml = $response->xml();
foreach($xml->Address as $address)
{
echo $address->Error->Description;
}
当然你也应该做一些错误检查等
此外,除了关于如何处理 PHP 中的 XML 数据的 examples in the documentation, there are tons of articles and answers here on SO 之外。如果您 运行 遇到问题,请务必检查它们。
我正在使用 Guzzle 调用 USPS 地址验证服务,并在响应中得到 XML。然后我使用以下方法从 XML 获取正文:
$body = $response->getBody();
产生以下内容:
<AddressValidateResponse>
<Address ID="0">
<Error>
<Number>-2147219400</Number>
<Source>clsAMS</Source>
<Description>Invalid City. </Description>
<HelpFile/>
<HelpContext/>
</Error>
</Address>
</AddressValidateResponse>
我需要对其进行解析以获取说明。
$body 当前是一个对象。我尝试将其转换为数组,但得到以下结果,这不是我想要的:
array (
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'stream' => NULL,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'size' => NULL,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'seekable' => true,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'readable' => true,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'writable' => true,
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'uri' => 'php://temp',
'' . "[=14=]" . 'GuzzleHttp\Psr7\Stream' . "[=14=]" . 'customMetadata' =>
array (
),
)
有谁知道如何解析 $body 以获得描述节点?
感谢您的指导!
在 PHP 中使用 XML 处理简单任务的最简单方法可能是通过 SimpleXML:
$xml = simplexml_load_string($body);
// Or if you're dealing with a Guzzle Response, you can even do
// $xml = $response->xml();
foreach($xml->Address as $address)
{
echo $address->Error->Description;
}
当然你也应该做一些错误检查等
此外,除了关于如何处理 PHP 中的 XML 数据的 examples in the documentation, there are tons of articles and answers here on SO 之外。如果您 运行 遇到问题,请务必检查它们。