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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?