Search code examples
phpxmllaravelxml-parsingsimplexml

Unable to parse xml from response


Hi I get this XML as response:

<?xml version="1.0"?>
<Response>
  <Environment>PRODUCTION</Environment>
  <Method/>
  <ResponseCode>03</ResponseCode>
  <ResponseDescription>Invalid Merchant</ResponseDescription>
  <Fee>0.00</Fee>
</Response>

Can someone tell me how do I parse it?

That xml I get if print $response->getBody()->getContents()

I try with simplexml_load_string($response->getBody()) and that gives me an error:

simplexml_load_string(): Entity: line 2: parser error : XML declaration allowed only at the start of the document

Also try with simplexml_load_string($response->getBody()->getContents()) like this:

$xml = simplexml_load_string($response->getBody()->getContents()); if ($xml === false) { echo "Failed loading XML: "; foreach(libxml_get_errors() as $error) { echo "<br>", $error->message; } } else { print_r($xml); }

it returns me only Failed loading XML: without any error.

Also try with $xml = new SimpleXMLElement($response->getBody()); and get this error: String could not be parsed as XML

Can you tell me what is the problem?


Solution

  • You should make sure that there are no white spaces in front of the xml declaration, these should always be the first bytes of an xml string.

    Try using trim to make sure this is so:

    simplexml_load_string(trim($response->getBody()));