dsaf32131 2015-06-18 08:32
浏览 33
已采纳

PHP:将xml转换为数组

I have an xml string. That xml string has to be converted into PHP array in order to be processed by other parts of software my team is working on. For xml -> array conversion i'm using something like this:

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

It works fine - most of the time :) The problem arises when my "xmlString" contains something like this:

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

Then, simplexml_load_string won't do it's job (and i know that's because of character "<"). As i can't influence any other part of the code (i can't open up a module that's generating XML string and tell it "encode special characters, please!") i need your suggestions on how to fix that problem BEFORE calling "simplexml_load_string".

Do you have some ideas? I've tried

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

but, that simply ruins entire "xmlString"... :(

  • 写回答

1条回答 默认 最新

  • duanqianwei2485 2015-06-18 09:58
    关注

    Well, then you can just replace the special characters in the $xmlString to the HTML entity counterparts using htmlspecialchars() and preg_replace_callback().

    I know this is not performance friendly, but it does the job :)

    <?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);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站