首页 > 解决方案 > DOMDocument 有时会返回混乱的字符

问题描述

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

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

3. (ca.) 之后的 DOM 运行: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());

有谁知道,该怎么办?

标签: phpdomdocumentphp-7.3

解决方案


我想这是因为站点压缩,您可以使用旧的 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());

推荐阅读