php - 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());
有谁知道,该怎么办?
解决方案
我想这是因为站点压缩,您可以使用旧的 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());
推荐阅读
- javascript - 如何在 React 中更改导入组件的 CSS 属性
- google-cloud-sdk - 在 Ubuntu 上安装 Google Cloud SDK 时出错,如何解决?
- r - 识别向量的第一次出现,其中 15 个值中有 12 个为 1
- sql-server - 无法使用变量执行 SQL Server 存储过程(找不到存储过程)
- c++ - 为 QDoubleSpinBox 的多个实例创建一个公共插槽
- javascript - 使用 javascript 设置 PHP 表单数组变量
- python - Python for loop variable(K) in range(1,11) 如何在 HHkC 之类的词中使用并显示 HH1C、HH2C......HH10C?
- postgresql - 在 Postgres 中插入多个表时是否保留顺序
- multi-tenant - 将项目级用户分配给多个租户
- spring - 如何使用集群中的所有 pod 订阅亚马逊 SNS 主题?