我有一个没有CDATA标签和嵌入式HTML的XML文档。如何提取此HTML以在PHP中进行操作以进行显示?
示例:
<?xml ...>
<main>
<book>
<title>Title of Book</title>
<description>
<p>Paragraph 1 describing book.<br />blah blah</p><p>2nd Paragraph</p>
</description>
</book>
</main>
我想将<p>Paragraph 1 describing book.<br />blah blah</p><p>2nd Paragraph</p>
提取到变量中。或使用simpleXML在php中显示回显。
我试过了:
$test = new SimpleXMLElement($xmlfile);
echo $test->{'main'}->{'book'}->{'description'};
我只是得到一个空白。
答案 0 :(得分:0)
您应首先在special symbols
xml
参考:http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
这可行。
$xml=<<<MMT
<main>
<book>
<title>Title of Book</title>
<description>
<p>Paragraph 1 describing book.<br />blah blah</p><p>2nd Paragraph</p>
</description>
</book>
</main>
MMT;
$xml = preg_replace('@<p>(.*?)</p>@','<p>$1</p>',$xml);
$xml = str_replace('<br />','<br />',$xml);
$data = simplexml_load_string($xml);
$str = $data->book->description;
$str = preg_replace('@<p>$1</p>@','<p>(.*?)</p>',$str);
$str = str_replace('<br />','<br />',$str);
echo $str;
或更好的方式,如果您只有一个循环,则可以为标准xml数据格式插入<![CDATA[
]]>
:
$xml=<<<MMT
<main>
<book>
<title>Title of Book</title>
<description>
<p>Paragraph 1 describing book.<br />blah blah</p><p>2nd Paragraph</p>
</description>
</book>
</main>
MMT;
$xml = preg_replace('@<description>(.*?)</description>@is','<description><![CDATA[\\1]]></description>',$xml);
$data = simplexml_load_string($xml);
$str = $data->book->description;
echo $str;
答案 1 :(得分:0)
尝试:
$test = new SimpleXMLElement($xmlfile);
echo $test->{'main'}->{'book'}->{'description'}->asXML();