MSF004
MSF004

Reputation: 159

Trying to Parse XML String from HTTP Request in PHP

As a preface: I cannot imagine this has not been asked before, but I have failed miserably at finding a solution...and I would think there is a simple solution and I am simply doing something completely wrong.

I have a simple index.php file that looks like so:

<?php
$data = file_get_contents('php://input');
echo "DATA : " . $data;

$xml = new SimpleXMLElement($data, 0, true);
echo "XML : " . $xml;

$RoundTrip = (string) $xml->RoundTrip;
$TransactionId = (string) $xml->TransactionId;

?>

The echo "DATA" shows:

<?xml version="1.0" encoding="utf-8"?><msg><head><Client>Test</Client><RoutingArea>811</RoutingArea><Source>MySRC</Source><Destination>BSRC</Destination><Version>2.27</Version><RoundTrip>ID=001088129291102</RoundTrip><TransactionId>12652b05-ceb9-11eb-a091-00505687f2ee</TransactionId><ServerId>03</ServerId></head><body><POdated>

...and the SimpleXMLElement is throwing an error:

PHP Warning:  SimpleXMLElement::__construct(): I/O warning : failed to load external entity &quot;&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&lt;msg&gt;&lt;head

As if the string is being read as URLencoded...but the initial output is not URLencoded.

My Goal is to: receive the XML doc from the request as a string and be able to parse it.

Upvotes: 2

Views: 910

Answers (2)

Top-Master
Top-Master

Reputation: 8816

It expects a file-path or URL, not file-content (because the 3rd parameter is true, while the default is false).

Try removing the 3rd parameter like:

$xml = new SimpleXMLElement($data, 0);

But if that does not work you still have the option:

$xml = simplexml_load_string($data);

// do something with $xml

Upvotes: 1

Mads Hansen
Mads Hansen

Reputation: 66783

The third parameter is $dataIsURL and you are specifying true.

https://www.php.net/manual/en/simplexmlelement.construct.php

dataIsURL

By default, dataIsURL is false. Use true to specify that data is a path or URL to an XML document instead of string data.

So, either change to false:

$xml = new SimpleXMLElement($tag, 0, false);

Or remove that third parameter:

$xml = new SimpleXMLElement($tag, 0);

Since you are providing a string and not a URL.

Upvotes: 0

Related Questions