DOMDocument 有时 return 乱七八糟的字符

DOMDocument sometimes return tangle of characters

我需要从 php 中的外部网站提取 DOM。我尝试测试 URL,但有时它会显示很多中文字母 :)(不过我更具体地说是 unicode 中的字符) 奇怪的是,如果我使用不同的 link,它会起作用,但是如果我使用下面的 link 和 运行 php 例如 3 次,在 3. 尝试后它停止工作(但对于 1、2。它显示正常 DOM 结构)

URL: https://www.csfd.cz/film/300902-bohemian-rhapsody/prehled/

DOM 后 3.(约)运行:https://i.stack.imgur.com/lnM1I.png

代码:

$doc = new \DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTMLFile("https://www.csfd.cz/film/300902-bohemian-rhapsody/prehled/");
dd($doc->saveHTML());

有人知道怎么办吗?

我猜是因为站点压缩,你可以使用good old curl:

提取数据
<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://www.csfd.cz/film/300902-bohemian-rhapsody/prehled/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');

$headers = array();
$headers[] = 'Connection: keep-alive';
$headers[] = 'Cache-Control: max-age=0';
$headers[] = 'Save-Data: on';
$headers[] = 'Upgrade-Insecure-Requests: 1';
$headers[] = 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36';
$headers[] = 'Dnt: 1';
$headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8';
$headers[] = 'Accept-Encoding: gzip, deflate, br';
$headers[] = 'Accept-Language: en-US;q=0.8,en;q=0.7,uk;q=0.6';
$headers[] = 'Cookie: nette-samesite=1; developers-ad=1;';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

$doc = new \DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($result);
dd($doc->saveHTML());