php - 如何用php dom html url?
问题描述
这是我要解析的 URL: http ://www.tsetmc.com/Loader.aspx?ParTree=151313&Flow=0
我使用 simple_html_dom.php 但它无法读取 HTML,因为 HTML 是编码的。
所以我认为我应该解析在线和网页源。有什么方法可以解析这个网站吗?
源代码如下所示:
<html>
<body>
<table class="table1">
<tbody>
<tr><th>***title</th>
<th class='ltr'>***99/2/24 12:10</th>
</tr>
<tr><td colspan="2">***message text here<hr /></td></tr>
</tbody>
</table>
</body>
我的代码:
<?php
require_once('simple_html_dom.php');
$url = "http://www.tsetmc.com/Loader.aspx?ParTree=151313&Flow=0";
$html = file_get_html($url);
foreach($html->find('th') as $element)
echo $element->src . '<br>';
?>
解决方案
正如您所指出的,问题是编码,它是gzip
编码的。您可以在 curl 中设置标志CURLOPT_ENCODING
来解决这个问题。它的作用,由 php-curl 文档提供:
“Accept-Encoding:”标头的内容。这使得能够对响应进行解码。支持的编码是“identity”、“deflate”和“gzip”。如果设置了空字符串“”,则会发送包含所有支持的编码类型的标头。
使用以下 php-curl 代码获取响应 html,如下所示:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://www.tsetmc.com/Loader.aspx?ParTree=151313&Flow=0",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "gzip",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>
$response
然后就可以直接使用response htmlsimple_html_dom.php
来解析dom树了。
这是代码的工作版本。 http://phpfiddle.org/main/code/gb66-3kzq
推荐阅读
- php - 如何检测 CLI PHP 进程/窗口是否使用“X”按钮关闭?
- python - 如何使用 Graph API 永久删除电子邮件?
- javascript - 有没有办法以 HTML 格式请求访问计算机上的本地存储?
- angular - 使用 akita-ng-fire 时如何避免“this.fireAuth.auth.createUserWithEmailAndPassword 不是函数”
- reactjs - 我已经成功启动了 npm,但是现在当我尝试点击 npm start 时,我发现下面提到的错误:
- node.js - 如何在我的 Google 操作中使用使用 Oauth 操场获得的刷新和访问令牌来调用 People API?
- rust - 如何使用 zbus 列出块设备?
- java - Maven构建依赖问题
- react-native - 如何在场景加载时禁用 iOS 反弹效果?
- javascript - 在 asp.net 网络表单中使用 Sweet 警报删除行