PHP:将 xml 转换为数组

PHP: Converting xml to array

我有一个 xml 字符串。 xml 字符串必须转换为 PHP 数组,以便我的团队正在处理的软件的其他部分进行处理。 对于 xml -> 数组转换,我使用的是这样的东西:

if(get_class($xmlString) != 'SimpleXMLElement') {
    $xml = simplexml_load_string($xmlString);
} 
if(!$xml) { 
    return false; 
} 

它工作正常 - 大多数时候 :) 当我的 "xmlString" 包含如下内容时出现问题:

<Line0 User="-5" ID="7436194"><Node0 Key="<1" Value="0"></Node0></Line0>

然后,simplexml_load_string 将无法完成它的工作(我知道那是因为字符“<”)。 因为我无法影响代码的任何其他部分(我无法打开生成 XML 字符串的模块并告诉它 "encode special characters, please!"),所以我需要您在调用之前就如何解决该问题提出建议"simplexml_load_string".

你有什么想法吗?我试过了

str_replace("<","&lt;",$xmlString)

但是,这只会毁掉整个 "xmlString"... :(

好吧,那么您可以使用 <a href="http://php.net/htmlspecialchars" rel="nofollow">htmlspecialchars()</a> and <a href="http://php.net/manual/en/function.preg-replace-callback.php" rel="nofollow">preg_replace_callback()</a>.[= 将 $xmlString 中的特殊字符替换为 HTML 实体对应项13=]

我知道这对性能不友好,但它确实有效:)

<?php
$xmlString = '<Line0 User="-5" ID="7436194"><Node0 Key="<1" Value="0"></Node0></Line0>';

$xmlString = preg_replace_callback('~(?:").*?(?:")~',
    function ($matches) {
        return htmlspecialchars($matches[0], ENT_NOQUOTES);
    },
    $xmlString
);

header('Content-Type: text/plain');
echo $xmlString; // you will see the special characters are converted to HTML entities :)

echo PHP_EOL . PHP_EOL; // tidy :)
$xmlobj = simplexml_load_string($xmlString);
var_dump($xmlobj);
?>