1

我有一个脚本,它本质上是一个索引新闻文章的爬虫。该脚本在一台服务器(主 http 服务器)上运行良好,但我正在尝试将其移至专用平台,其中一个部分将无法运行。

失败的部分使用一个简单的函数(来自 SO)来检查字符串(爬虫找到的 url)是否与本地存储在 .txt 文件中的排除列表匹配。

我已经测试以确保使用 var_dump 接收到 .txt 文件并且一切正常。

这始终无法取消设置或回显正数,但在另一台服务器上一切正常。

重要的部分如下:

<?php
ini_set('display_errors', 1);
$linkurl_reg = '/href="http:\/\/metro.co.uk(.+?)"/is';    


function endsWith($haystack, $needle)
{
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}

$data = file_get_contents("http://metro.co.uk");
preg_match_all($linkurl_reg,$data,$new_links);

$exclusion_list = explode("\n",file_get_contents('../F/exclusion_list.txt'));

var_dump($exclusion_list); //just to check we got the file ok

for($i = '0';$i < count($new_links[1]) ; $i++){
        for ($ii = '0';$ii < count($exclusion_list);$ii++){
        if(endsWith($new_links[1][$i], $exclusion_list[$ii])){echo 'unset ';unset($new_links[1][$i]);}else{echo'not unset ';}
        }
    }


?> 

奇怪的是,如果我在设置排除列表时只使用一个值,例如

$exclusion_list[0] = "xmlrpc.php"; 

代替

$exclusion_list = explode("\n",file_get_contents('../F/exclusion_list.txt'));

它适用于该特定字符串。

如果有人有任何想法,我已经盯着这个看了 3 天,完全被难住了。

我尝试过的事情:

在爆炸之前将 $exclusion_list 数组编码为 UTF。

在循环中将 $exclusion_list 字符串编码为 UTF

用普通字符串测试函数

手动写入字符串,而不是从数组或 fileget 中写入(很烦人)

将文件扩展名从 .txt 更改为其他各种内容

更新服务器上的 php 版本(非工作版本)

在分解期间将“\n”替换为“\r”和“\n\r”

我什至尝试将函数更改为在 SO 上找到的其他一些函数,奇怪的是我得到了相同的结果(适用于我定义的字符串,但不适用于从 exclude_list 文件中检索到的任何内容)。

对于我的一生,我不知道为什么一个会工作而不是另一个。

当前 PHP 版本:5.4.36-0+deb7u3(非工作服务器)

当前 PHP 版本:5.2.17(工作服务器)

为 $exclusion 列表请求 var_dump(非工作服务器):

array(9) {
  [0]=>
  string(6) ".jpeg"
  [1]=>
  string(5) ".jpg"
  [2]=>
   string(5) ".gif"
  [3]=>
  string(5) ".css"
  [4]=>
  string(5) ".xml"
  [5]=>
  string(11) "xmlrpc.php"
  [6]=>
  string(21) "metro.co.uk" target="
  [7]=>
  string(20) "metro.co.uk/osd.xml"
  [8]=>
  string(32) "metro.co.uk/terms/#privacypolicy"
}

为 $exclusion 列表(工作服务器)请求 var_dump:

array(9) {
  [0]=>
  string(5) ".jpeg"
  [1]=>
  string(4) ".jpg"
  [2]=>
  string(4) ".gif"
  [3]=>
  string(4) ".css"
  [4]=>
  string(4) ".xml"
  [5]=>
  string(10) "xmlrpc.php"
  [6]=>
  string(20) "metro.co.uk" target="
  [7]=>
  string(19) "metro.co.uk/osd.xml"
  [8]=>
  string(32) "metro.co.uk/terms/#privacypolicy"
}

两台服务器都是linux,两个文本文件都不是在windows平台上构建或编辑的

4

3 回答 3

1

确保 *.txt 文件中的行由 \n 而不是 \r\n 分隔,如果您保存在 Windows 程序中,则会发生这种情况。

否则,在您使用 '\n' 将其分解后,字符串将全部以 '\r' 结尾,因此可能无法满足 endsWith() 条件

此代码应适用于两台机器:

$exclusion_list = explode("\n",str_replace("\r", "", file_get_contents('../F/exclusion_list.txt')));
于 2015-02-18T16:54:21.397 回答
0

如果您的服务器或计算机之一使用 Windows,则行尾编码可能存在问题:Windows 上的 \r\n 和 unix 上的 \n (我认为 iOS 上的 \r,但我不确定)

于 2015-02-18T16:51:53.797 回答
0

可能是文件中的一些问题,尝试使用其他文件并检查它是否显示相同的问题。

于 2015-02-18T17:14:09.527 回答