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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?