如何使用SimpleXML解析XML的CDATA HTML内容?

时间:2013-04-06 09:28:50

标签: php html xml rss simplexml

我正在尝试将Xml内容显示到表格中,所有内容都完美无缺,但标签中的一些内容我不想显示,我只想要图像而不是

2012年11月的日历5.10测试

,如xml,

 <content:encoded><![CDATA[<p>November 2012 calendar from 5.10 The Test</p>
    <p><a class="shutterset_" href='http://trance-gemini.com/wordpress/wp-content/gallery/calendars/laura-bertram-trance-gemini-145-1080.jpg' title='&lt;br&gt;November 2012 calendar from 5.10 The Test&lt;br&gt; &lt;a href=&quot;</a></p>]]>
</content:encoded> 

我想显示图像但不是

2012年11月日历从5.10测试

<?php
// load SimpleXML
$item = new SimpleXMLElement('test1.xml', null, true);

echo <<<EOF
<table border="1px">
        <tr cl>

        </tr>       
EOF;
foreach($item->channel->item as $boo) // loop through our books
{
        echo <<<EOF

         <tr>
            <td rowspan="3">{$boo->children('content', true)->encoded}</td>
            <td>{$boo->title}</td>   
        </tr>

        <tr>
           <td>{$boo->description}</td>
        </tr>

        <tr>
           <td>{boo->comments}</td>
        </tr>
EOF;
}
echo '</table>';
?>

2 个答案:

答案 0 :(得分:6)

我曾经回答过,但我找不到答案了。

如果你看一下字符串(简化/美化):

<content:encoded><![CDATA[
    <p>Lorem Ipsom</p>
    <p>
      <a href='laura-bertram-trance-gemini-145-1080.jpg' 
         title='&lt;br&gt;November 2012 calendar from 5.10 The Test&lt;br&gt; &lt;a href=&quot;</a>
    </p>]]>
</content:encoded> 

您可以看到您在<{1}}元素的节点值中编码 的HTML编码。首先,您需要获取已经执行的HTML值:

<content:encoded>

然后您需要解析$html = $boo->children('content', true)->encoded; 内的HTML。使用PHP可以使用哪些库进行HTML解析:

如果您决定对作业使用或多或少的推荐$html,则只需获取某个元素的属性值:

或者你已经使用它的姐妹库SimpleXML(所以更推荐这个,请参阅下一节):


  

在您的问题的上下文中,以下提示:

您正在使用SimpleXML。 DOMDocument是一个姐妹库,这意味着你可以在两者之间进行交换,这样你就不需要学习一个全新的库了。

例如,您只能使用DOMDocument的HTML解析功能,但会将其导入DOMDocument。这很有用,因为SimpleXML不支持HTML解析。

通过simplexml_import_dom()工作。

简化的分步示例:

SimpleXML

现在,您可以将// get the HTML string out of the feed: $htmlString = $boo->children('content', true)->encoded; // create DOMDocument for HTML parsing: $htmlParser = new DOMDocument(); // load the HTML: $htmlParser->loadHTML($htmlString); // import it into simplexml: $html = simplexml_import_dom($htmlParser); 用作表示HTML文档的新SimpleXMLElement。由于您的HTML块没有任何$html标记,因此根据HTML规范,它们会放在<body>标记内。这样,您就可以访问示例中第二个<body>元素中第一个href的{​​{1}}属性:#

<a>

这里是上面的完整视图(Online Demo):

<p>

它输出的内容:

// access the element you're looking for:
$href = $html->body->p[1]->a['href'];

答案 1 :(得分:-3)

您需要解析图片网址,例如通过preg_match和此正则表达式'(http://(?:[^']*))'