0

I’m using Guzzle to call the USPS Address Validation Service, and getting XML in the response. I then get the body from the XML using the following:

$body = $response->getBody();

Which produces the following:

<AddressValidateResponse>
    <Address ID="0">
        <Error>
            <Number>-2147219400</Number>
            <Source>clsAMS</Source>
            <Description>Invalid City.  </Description>
            <HelpFile/>
            <HelpContext/>
        </Error>
    </Address>
</AddressValidateResponse> 

I need to parse that to get the Description.

$body is currently an Object. I tried casting it to an Array, but get the following, which is not what I’m after:

array (
  '' . "\0" . 'GuzzleHttp\\Psr7\\Stream' . "\0" . 'stream' => NULL,
  '' . "\0" . 'GuzzleHttp\\Psr7\\Stream' . "\0" . 'size' => NULL,
  '' . "\0" . 'GuzzleHttp\\Psr7\\Stream' . "\0" . 'seekable' => true,
  '' . "\0" . 'GuzzleHttp\\Psr7\\Stream' . "\0" . 'readable' => true,
  '' . "\0" . 'GuzzleHttp\\Psr7\\Stream' . "\0" . 'writable' => true,
  '' . "\0" . 'GuzzleHttp\\Psr7\\Stream' . "\0" . 'uri' => 'php://temp',
  '' . "\0" . 'GuzzleHttp\\Psr7\\Stream' . "\0" . 'customMetadata' => 
  array (
  ),
)  

Does anyone know how I can parse that $body to get the Description Node?

Thanks for any guidance!

RobertFrenette
  • 629
  • 3
  • 8
  • 29

1 Answers1

2

The probably easiest way to handle simple tasks with XML in PHP is through 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;
}

Of course you should also do some error checking etc.

Also, besides the examples in the documentation, there are tons of articles and answers here on SO on how to handle XML data in PHP. Make sure to check them out if you run into problems.

Community
  • 1
  • 1
Quasdunk
  • 14,944
  • 3
  • 36
  • 45