SimpleXML 在具有相同 PHP 版本的两个不同服务器上生成的两个不同输出

Two different outputs generated by SimpleXML on two different servers with the same PHP version

我有这个代码:

$feed = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><rss version="2.0" xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" />', LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_ERR_FATAL);
$channel = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><channel></channel>', LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_ERR_FATAL);
$counter = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><yandex:analytics>test</yandex:analytics>', LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_ERR_FATAL);

$toDom = dom_import_simplexml($channel);
$fromDom = dom_import_simplexml($counter);
$toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));

$toDom = dom_import_simplexml($feed);
$fromDom = dom_import_simplexml($channel);
$toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));

$dom = new DOMDocument('1.0', 'UTF-8');
$dom->appendChild($dom->importNode(dom_import_simplexml($feed), true));
$dom->formatOutput = true;

var_dump($feed->saveXML());

现在,在一台服务器上输出是:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><yandex:analytics>test</yandex:analytics></channel></rss>

第二个输出是:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:yandex="http://news.yandex.ru" xmlns:media="http://search.yahoo.com/mrss/" xmlns:turbo="http://turbo.yandex.ru" version="2.0"><channel><analytics>test</analytics></channel></rss>

两台服务器的 PHP 版本相同:7.1.30 我在两个 phpinfo() 中注意到的唯一 xml 相关差异是第一个 libxml2 2.9.9 和另一个 2.7.6.

旧的是一个旧的CentOS 6系统,不幸的是现在不能升级,我什至不确定这是不是libxml2的错。

现在的问题是我有一个依赖更新行为的库。

确定与libxml2有关吗?

是否可以根据第一个行为在不丢弃库的情况下以某种方式解决它?

$counterXML无效,因为你现在有...

$counter = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?>
         <yandex:analytics>test</yandex:analytics>', 
     LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_ERR_FATAL);

<yandex:analytics> 使用的命名空间未在 XML 本身中定义。

您应该更改它以定义命名空间...

<yandex:analytics xmlns:yandex="http://news.yandex.ru">test</yandex:analytics>

或者您可以通过在添加之前手动创建元素来添加...

$fromDom = $toDom->ownerDocument->createElementNS("yandex", "yandex:analytics", "test");