首页 > 解决方案 > 如何用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>';
?>

标签: phpdom

解决方案


正如您所指出的,问题是编码,它是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


推荐阅读