今天用PHP解析xml文档 大致如下内容:
<description>
<![CDATA[<a href='http://xx.com'>a link</a>]]>
</description>用simplexml_load_string无法读到description中间的内容,各位有什么高招?我先说一下我的思路,尽管最终失败,算是抛砖引玉吧
第一步,我先讲上述字符串整理成如下形式:<description>
<a href='http://xx.com>a link'></a>
</description>
第二步我打算将<a href='http://xx.com>a link'></a>部分的“<”和">"替换为&lt;或者&gt;形式;如下:$str = preg_replace("/<description>(.*?)<\/description>/", search("$1"), $str); 
function search($match){
$match = str_replace("<", "x", $match);
return $match; 
}
但是我发现回调函数中str_replace函数无法执行;各位可有什么思路或者解决办法,谢谢;

解决方案 »

  1.   


    $str ="<description>
    <a href='http://xx.com>a link'></a>
    </description>";
    function search($match){
    $match = str_replace("<", "x", $match[1]); 
    return $match;  
    }
    echo preg_replace_callback("/<description>(.*?)<\/description>/s", "search", $str); 
    //xa href='http://xx.com>a link'>x/a>
      

  2.   

    直接用Rss的一个解析器就行啊
      

  3.   

    $parser = xml_parser_create();
    xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, false);
    xml_parse_into_struct($parser, $xmldata, $result_xml, $result_idx);
    xml_parser_free($parser);
    可以解析到
      

  4.   

    谁说不可以$xml = <<< XML
    <?xml version="1.0"?>
    <root>
    <show>
    <description>
    <![CDATA[<a href='http://xx.com'>a link</a>]]>
    </description>
    </show>
    </root>
    XML;$xmlRoot = simplexml_load_string($xml);$ar = array();foreach($xmlRoot as $val){
       $ar[] = (string) $val->description;
       } 
    print_r($ar);
    Array
    (
        [0] => 
    <a href='http://xx.com'>a link</a>
     
    )