2012-04-03 35 views
1

在一个WordPress博客中,我使用以下函数来抓取页面(单张张视图)并找到第一张图片,如果找不到,则使用默认图片:PHP函数来抓取第一张图片

function catch_that_image() { 
    global $post, $posts; 
    $first_img = ''; 
    ob_start(); 
    ob_end_clean(); 
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
    $first_img = $matches [1] [0]; 

    if(empty($first_img)){ //Defines a default image 
    $first_img = "http://custome_url_for_default_image.png"; 
    } 
    return $first_img; 
} 

我试图将它粘贴到Tumblr主题中,但遇到一些问题(它不作为PHP函数加载)。当然,我错过了一些东西。如果任何人有解决这个问题的想法,我会很乐意尝试。

感谢,

P.

+0

你的意思是 “刮”? – mmcglynn 2012-04-03 18:17:03

+0

对不起:网页抓取,抓取,收获......我也意识到我需要PHP脚本的开始和结束标记,但添加它们并不会使该功能起作用。 – Parneix 2012-04-03 18:29:16

回答

5

做到这一点,最好的办法是avoid using regexes to parse HTML

尝试使用DOM文档:

function catch_that_image() { 
    global $post; 
    $dom = new DOMDocument(); 
    $dom->loadHtml($post->post_content); 
    $imgTags = $dom->getElementsByTagName('img'); 
    if ($imgTags->length > 0) { 
     $imgElement = $imgTags->item(0); 
     return $imgElement->getAttribute('src'); 
    } else { 
     return 'http://custome_url_for_default_image.png'; 
    } 
} 
+0

这也是我用来解决这个问题的确切策略。 DOMDocument可以非常优雅地解决这个问题。布拉沃。 – 2012-04-03 19:18:39

+0

它确定似乎更清洁,我很高兴了解编码这种功能的“正统”或正确的方式。尽管我使用开放和关闭的PHP标签并确保将函数包含在PHP代码中,但我仍然在做一些错误的事情,因为代码不能用作PHP代码:它的一部分实际上出现在我的网站上(它是可见的) ''。我会做更多的测试并试图弄清楚。谢谢你的建议。 – Parneix 2012-04-03 20:40:26

+0

[更新]显然(如果我没有错)Tumblr的主题不支持PHP代码...我的这一个不好。虽然可能有一种解决方法:在自主服务器上托管PHP脚本并在主题内调用它。但这就是全新的球赛。感谢您的支持! – Parneix 2012-04-03 21:20:53