从<content:encoded> </content:encoded>获取图像src

时间:2014-11-23 08:24:31

标签: php xml simplexml

我试图从<content:encoded>获取一个img网址并将网址插入我的数据库

但我似乎无法从xml文件中获取正确的信息 -

或者无法使用simpleXML检索数据?

这是我的XML

<item>
  <title>Movietitle</title>
  <content:encoded><![CDATA[<p>
    <img class="aligncenter  wp-image-22085" src="movie-poster-694x1024.jpg" alt="Predestination 2014" width="475" height="701" /></p>
    <p><span id="more-22087"></span></p>
    <p>
    <a href="http://bit.ly/1za5mIz" target="_blank">
    <h4 style="text-align: left;">Release Info:</h4>
    Genre: Sci-Fi, Thriller<br />
    Quality: DVDRip<br />
    Language: English</p>]]>
    </content:encoded>
</item>

PHP

$feeds = array('http://xxxx.xml');
foreach( $feeds as $feed ) {

    $xml = simplexml_load_file($feed);

    foreach($xml->channel->item as $item) {

        $video_title = $item->title;
        $video_img=(string) $item->children($ns['content']);


        $sql = "INSERT INTO video (video_title, video_img, video_date) VALUES (:video_title, :video_img, NOW())";
        $query = $dbh->prepare($sql);
        $query->execute(array(
            ':video_title' => $video_title,
            ':video_img' => $video_img
        ));     
    } 
}

1 个答案:

答案 0 :(得分:4)

是的,有可能,只需跟进->children(),然后将内容视为HTML。在这种情况下,您可以使用DOMDocument,然后使用->getAttribute('src')获取图片代码的来源。

示例:

$xml = simplexml_load_file('http://axxomovies.org/feed', null, LIBXML_NOCDATA);
foreach ($xml->channel->item as $item) {
    $title = (string) $item->title;
    $content = $item->children('content', 'http://purl.org/rss/1.0/modules/content/');
    $html_string = $content->encoded;
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($html_string);
    libxml_clear_errors();
    $img = $dom->getElementsByTagName('img')->item(1)->getAttribute('src');
    echo 'Title: ' . $title . '<br/>';
    echo 'Image source: ' . $img;
    echo '<hr/>';
}

旁注:您不需要准备每次迭代。您可以将其取出并将其放在循环上方。你只需准备一次。

相关问题