0

我正在查看页面源代码,基本上想获取“og:image”图像网址

我正在使用以下内容,它有效,并且我认为(除了相对 URL 问题)涵盖了所有可能性 - 但这可能不是最有效的方法 - 我已经评论了代码以显示每一行正在做什么($ html是源代码):

$og_img = explode( '<meta property="og:image" content=', $html); // strip out beginning
$og_img = explode('>', $og_img[1]); // strip out end
if(substr($og_img[0], -1)=='/'){ $og_img[0] = substr($og_img[0], 0, -1); } // strip / if used /> to close the tag
$og_img[0] = str_replace("'", "", $og_img[0]); // strip ' ... ' apostrophes if used
$og_img[0] = str_replace('"', '', $og_img[0]); // strip " ... " doubke quotes if used

有没有更有效的方法?

4

1 回答 1

0

不要自己滚。

去使用 DOM。例如

$doc = new DOMDocument();
@$doc->loadHTML($html);
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('property') == 'og:image')
        $og_image_content = $meta->getAttribute('content');
}

或(虽然没有尝试过)使用:

get_meta_tags()
于 2012-08-30T09:41:10.740 回答