2011-11-05 41 views
0

我有一個沒有CDATA標籤和嵌入​​式HTML的XML文檔。我如何提取這個HTML來操縱它在PHP中顯示?如何從XML文檔中檢索HTML塊w/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

應先xml

參考轉移special symbolshttp://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>@','&lt;p&gt;$1&lt;/p&gt;',$xml); 
$xml = str_replace('<br />','&lt;br /&gt;',$xml); 
$data = simplexml_load_string($xml); 
$str = $data->book->description; 
$str = preg_replace('@&lt;p&gt;$1&lt;/p&gt;@','<p>(.*?)</p>',$str); 
$str = str_replace('&lt;br /&gt;','<br />',$str); 
echo $str; 

或更好的方法,如果你只有一個迴路,可以插入<![CDATA[]]>爲標準的XML數據formart:

$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; 
+0

此XML來自第3第三方,他們無法添加CDATA,但現在增加你的方式似乎非常明顯,我只是修改爲接受標記正則表達式中的屬性。 – user663581

0

嘗試:

$test = new SimpleXMLElement($xmlfile); 
echo $test->{'main'}->{'book'}->{'description'}->asXML();