为什么 cURL 返回空字符串?
2022-08-30 19:30:20
我在PHP的cURL返回一个带有一些URL的空字符串时遇到问题。我正在尝试解析不同网页的OG元数据,它适用于我尝试过的所有网站,除了NYTimes。这是我到目前为止的代码。
print_r(get_og_metadata('http://somewebsite.com'));
public function get_data($url)
{
$ch = curl_init();
$timeout = 5;
// the url to fetch
curl_setopt($ch, CURLOPT_URL, $url);
// return result as a string rather than direct output
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// set max time of cURL execution
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public function get_og_metadata($url)
{
libxml_use_internal_errors(TRUE);
$data = $this->_get_data($url);
$doc = new DOMDocument();
$doc->loadHTML($data);
$xpath = new DOMXPath($doc);
$query = '//*/meta[starts-with(@property, \'og:\')]';
$metadatas = $xpath->query($query);
$result = array();
foreach($metadatas as $metadata)
{
$property = $metadata->getAttribute('property');
$content = $metadata->getAttribute('content');
$result[$property] = $content;
}
return $result;
}