【问题标题】:How to use file_get_contents or file_get_html?如何使用 file_get_contents 或 file_get_html?
【发布时间】:2013-02-04 10:07:19
【问题描述】:

我已经阅读了很多关于这里的问题,但我不确定是否应该使用file_get_contentsfile_get_html

我要做的就是使用 PHP 在我的网站上显示此页面上的两个表格:http://www.statmyweb.com/recently-analyzed/

我当然知道如何获取他们的完整页面并将其显示在我的网站上,但我无法弄清楚我如何能够在不获取页眉/页脚的情况下仅拉出这两个表格。

【问题讨论】:

  • @Mark Ba​​ker,simple-html-dom 标签可能是个好线索
  • @pguardiario - 是的,我应该注意到了

标签: php file-get-contents simple-html-dom


【解决方案1】:

您不能在file_get_contents() 中指定只是为了检索表。

您必须使用以下方法获取 file_get_contents() 的返回值:

$result = file_get_contents("urlHere");

然后分析$result变量,提取需要输出什么信息。

【讨论】:

    【解决方案2】:

    通过file_get_contents() 获取完整的网站内容,然后将preg_match 应用于您通过<table></table> 获得的内容。这将为您带来表格标签下的所有内容。在您的网页中显示它时,只需输入一个<table>,然后回显您匹配的内容并在末尾添加一个</table>

    【讨论】:

    • +1 这会很痛苦(尤其是当有 simple_html_dom 之类的工具可用时),但肯定会起作用。
    • 它适用于这个特定示例,但在某些其他情况下会失败,例如table 中有嵌套的table 元素时
    • 如前所述,正则表达式函数代表该任务的次优工具。
    【解决方案3】:

    您需要file_get_html,因为file_get_contents 会将响应正文加载到字符串中,而file_get_html 会将其加载到simple-html-dom 中。

    $dom = file_get_html($url);
    $tables = $dom->find('table');
    echo $tables[0];
    echo $tables[1];
    

    您也可以将file_get_contentsstr_get_html 一起使用:

    $dom = str_get_html(file_get_contents($url));
    

    但那会很愚蠢。

    【讨论】:

    • 你如何在字符串中覆盖 $dom,它有类似的字符串,我们可以通过 file_get_content 获取,或者我们是否可以使用任何其他函数(如 file_get_content)从 $dom 获取字符串
    • 通常情况下,这会很愚蠢。除非由于限制(例如 allow_url_fopen 已关闭),您可能无法使用 file_get_contents 或 file_get_html,在这种情况下,您可能会使用 curl 收集字符串,然后使用 str_get_html。不是真正的 OP 问题,但它可能对某人有所帮助....
    猜你喜欢
    • 2014-08-25
    • 2019-09-10
    • 1970-01-01
    • 2016-08-29
    • 2013-11-17
    • 1970-01-01
    • 2018-09-25
    • 2010-12-30
    相关资源
    最近更新 更多