【问题标题】:PHP: Use every line from txt to do this?PHP:使用 txt 中的每一行来执行此操作?
【发布时间】:2013-05-12 09:44:04
【问题描述】:

尝试编写一个脚本,从 txt 中获取一行(行是 url),转到该 url,搜索并获取特定数据。抓取数据有效,但我需要多次这样做。这是 find and get sn -p 它工作正常。

    include(dom.txt);
    $html = file_get_html('url here');
    foreach($html->find('a.live') as $e)
    echo (''.$e->innertext.'<br />');

这是我到目前为止所做的,但我收到一个错误“警告:file_get_contents(Array)”

    <?php
    include ("dom.php");
    $file = fopen("urls.txt", "r");
    $i = 0;
    while (!feof($file)) {
    $line[] = fgets($file);
    }
    fclose($file);
    foreach ($line as $x){
    $html = file_get_html("$line");
    foreach($html->find('a.live') as $e)
    echo (''.$e->innertext.'<br />');
    }
    ?>

有人可以帮忙吗? :(

编辑更改 $html = file_get_html("$line"); $html = file_get_html("$x");但还是报错

Edit 2 脚本有效,但我认为它会覆盖结果并且只显示最后一个结果

【问题讨论】:

    标签: php while-loop line


    【解决方案1】:

    您将数组$line 传递给函数file_get_html,它只接受字符串。

    您确实将 foreach 循环设置为遍历数组。请改用file_get_html($x)

    【讨论】:

    • 感谢好友编辑了该内容,但仍然收到错误警告:file_get_contents() [function.file-get-contents]:第 151 行 /home/a6180322/public_html/dom.php 中的文件名不能为空
    • 你可以尝试做一个 var_dump($line),看看数组的元素是否为空?
    • 在您的 file_get_html 行之前添加一个if (empty($x)) continue;,这将跳过文件中的所有空行
    • fullybaked urls.txt 有 2 个测试链接,结果必须是第一个测试链接的 1 个 url 和第二个测试链接的 2 个 url。它可以工作,但会显示第二个测试链接的结果。我认为它会覆盖它
    【解决方案2】:

    这一行:

    $html = file_get_html("$line");
    

    应该是:

    $html = file_get_html("$x");
    

    正如mastergalen 所指出的,没有理由将$x 包含在引号中。它不会为您带来任何好处,只会为口译员增加更多工作。

    还值得注意的是,fgets 将在返回值中包含一个换行符,您可能需要在处理它之前从 url 中修剪它。

    【讨论】:

      【解决方案3】:

      您可以使用file() 函数,它将文件路径作为参数并返回行数组。

       <?php
       $aLines = file('/path/to/file');
      
       foreach( ( is_array( $aLines) ? $aLines : array() ) as $sLine )
       {
            // do what you have to do
            $html = file_get_html($sLine);
            foreach($html->find('a.live') as $e)
                 echo (''.$e->innertext.'<br />');
       }
       ?>
      

      【讨论】:

      • 致命错误:无法在第 171 行的 /home/a6180322/public_html/dom.php 中重新声明 file_get_html()(之前在 /home/a6180322/public_html/dom.php:141 中声明)
      • 您的错误来自代码的不同部分 - 您能提供吗?
      • 您可能在某些循环中包含的文件中有以下行include('dom.php')。您应该将其更改为 require_once() - 该文件将仅包含一次。
      猜你喜欢
      • 2016-04-14
      • 2013-01-28
      • 2021-10-27
      • 2016-05-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 2014-11-12
      相关资源
      最近更新 更多