尝试从 PHP 中的 HTTP 请求解析 XML 字符串

问题描述

作为序言:我无法想象以前没有人问过这个问题,但我在找到解决方案方面惨遭失败……我认为有一个简单的解决方案,而我只是做错了一些事情。

我有一个简单的 index.PHP 文件,如下所示:

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

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

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

?>

回声“DATA”显示

<?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>

...并且 SimpleXMLElement 抛出错误

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

好像字符串被读取为 URLencoded...但初始输出不是 URLencoded。

我的目标是:从请求中以字符串形式接收 XML 文档并能够解析它。

解决方法

它需要一个文件路径或 URL,而不是文件内容(因为第三个参数是 true,而默认是 false)。

尝试删除第三个参数,例如:

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

但如果这不起作用,您仍然可以选择:

$xml = simplexml_load_string($data);

// do something with $xml
,

第三个参数是 $dataIsURL,您指定的是 true

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

dataIsURL

默认情况下,dataIsURL 为 false。使用 true 指定数据是 XML 文档的路径或 URL,而不是字符串数据。

因此,要么更改为 false

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

或者删除第三个参数:

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

因为您提供的是字符串而不是网址。