【问题标题】:PHP Script to download a webpage's source code and search for a specific string用于下载网页源代码并搜索特定字符串的 PHP 脚本
【发布时间】:2012-05-25 17:22:41
【问题描述】:

我需要帮助编写完成以下任务的 PHP 代码:

  1. 访问网站 (www.example.com)
  2. 将其源代码下载到字符串变量中
  3. 在此特定字符串中搜索特定内容,例如

    <div class="news" title="news alert">Click to get news alert</div>

基本上我需要搜索title="news alert"的源代码

谢谢大家,

【问题讨论】:

  • 你想从有title="news alert"的元素返回什么?

标签: php


【解决方案1】:

你可以使用PHP DOM:

$text = file_get_contents('http://example.com/path/to/file.html');
$doc = new DOMDocument('1.0');
$doc->loadHTML($text);
foreach($doc->getElementsByTagName('div') AS $div) {
    $class = $div->getAttribute('class');
    if(strpos($class, 'news') !== FALSE) {
        if($div->getAttribute('title') == 'news alert') {
            echo 'title found';
        }
        else {
            echo 'title not found';
        }
    }
}

或者可能是Query Path,它试图模拟 jQuery 服务器端:

$text = file_get_contents('http://example.com/path/to/file.html');
if(qp($text)->find('div.news[title="news alert"]')->is('*')) {
    echo('title found');
}
else {
    echo('title found');
}

【讨论】:

    【解决方案2】:

    您可以使用DOMXPath 找到它:

    $dcmnt = new DOMDocument(); $dcmnt->loadHTML( $cntnt );
    $xpath = new DOMXPath( $dcmnt );
    $match = $xpath->query("//div[@title='news alert']");
    
    echo $match->length ? "Found" : "Not Found" ;
    

    演示:http://codepad.org/CLdE8XCQ

    【讨论】:

    • 我编写了一个小 CMS,它从数据库模式构造 XML,并使用 XSLT 进行模板化。 XSLT 中的 XPath 查询被视为对象。因此将它们用作字符串是错误的,您必须先将它们转换为字符串。那个菜鸟的错误让我损失了几个小时。因此 DOMXpath 根深蒂固的恐惧症。
    【解决方案3】:

    这很简单:

    $html = file_get_contents('http://site.com/page.html');
    if (strpos($html,'title="news alert"')!==false)
     echo 'title found';
    

    【讨论】:

    • strpos ( 字符串 $haystack , 混合 $needle [, int $offset = 0 ] )
    • 不用投反对票,下次改错就行了
    • @yes123 在对答案进行编辑之前,StackOverflow 不允许您更改投票。
    【解决方案4】:
    $page = file_get_contents('http://www.example.com/');
    if(strpos($page, "title=\"news alert\"")!==false){
        echo 'title found';
    }
    

    【讨论】:

      【解决方案5】:
      $url = 'http://www.example.com/';
      $page = file_get_contents($url);
      
      if(strpos($page, 'title="news alert"') !==false || strpos($page, 'title=\'news alert\'') !==false)
      {
          echo 'website with news alert found';
      }
      else
      {
          echo 'website not found';
      }
      

      【讨论】:

        猜你喜欢
        • 2012-10-09
        • 1970-01-01
        • 1970-01-01
        • 2017-09-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多