【问题标题】:How do to get specific data from a webpage using PHP如何使用 PHP 从网页中获取特定数据
【发布时间】:2012-04-21 00:58:28
【问题描述】:

我试图使用 PHP 和 file_get_contents 以及正则表达式从网页中获取数据,但我似乎无法从页面中获取正确的数据。

这是我的代码,

<?php
   $homepage = file_get_contents('http://www.website.com');
   preg_match_all('/<p><b>(.*)<\ /b><br>(.*)<br>(.*)<\ /p>/ms', $homepage, $matches);
   $def = $matches[0];
   echo $def;
   ?>

即使有与表达式匹配的 html 代码,我的正则表达式也没有提取任何内容。作为测试,我还尝试将第一个 preg_match 函数替换为以下函数。

preg_match_all('/<div>(.*)<\ /div>/ms', $homepage, $matches);

这仅提取了页面上众多 div 标签中的 2 个。我的代码有什么问题,正确的编写方式是什么?

谢谢

【问题讨论】:

    标签: php regex


    【解决方案1】:

    您可以简单地使用 PHP 的 Document Object Model,而不是使用 RegEx。

    $homepage = file_get_contents('http://www.website.com');
    $DOM = new DOMDocument;
    $DOM->loadHTML($homepage);
    $items = $DOM->getElementsByTagName('div');
    $def = $items->item(0)->nodeValue;
    

    (参考表格this问题)。

    【讨论】:

      猜你喜欢
      • 2015-09-16
      • 2012-07-19
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多