-1

我正在尝试使用 php 获取元数据,例如 og:image、title 或 description。

我正在使用该代码:

<?php
$sites_html = file_get_contents($url);

$html = new DOMDocument();
@$html->loadHTML($sites_html);
$meta_og_img = null;
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
    //If the property attribute of the meta tag is og:image
    if($meta->getAttribute('property')=='og:image'){
        //Assign the value from content attribute to $meta_og_img
        $meta_og_img = $meta->getAttribute('content');
    }
}
echo $meta_og_img;
?>

当我使用这个网址时(https://www.elmundo.es/papel/2019/01/28/5c4ed8effc6c83d2718b4605.html)它工作得很好但是当我使用这个网址时(https://andresmartin.org/2016/09/正念-la-fibromialgia-mirar-dolor-amabilidad-alivia-malestar-reduce-dolor/),我得到了错误。

我怎样才能避免这个错误?如果不可能,我怎样才能用另一种方法获取元数据?

我认为这并不重要,但我正在使用 laravel。

编辑:这是错误的屏幕截图https://pasteboard.co/HYPI7KV.png

4

1 回答 1

0

最后我找到了方法。

我补充说:

$context = stream_context_create(
    array(
        "http" => array(
        "header" => "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
        )
    )
);
$sites_html = file_get_contents('https://andresmartin.org/2016/09/mindfulness-la-fibromialgia-mirar-dolor-amabilidad-alivia-malestar-reduce-dolor/', false, $context);

现在它工作正常。

于 2019-01-30T12:23:15.217 回答