【问题标题】:file_get_contents and variablesfile_get_contents 和变量
【发布时间】:2012-03-25 10:17:09
【问题描述】:

我有一个包含 ID 列表的文本文件。 使用 PHP,我正在尝试为每个 ID 加载一个 url 并从该页面中提取一些内容(另一个 id)

例如,如果我的 ID 为 555、888、222 我想加载 URL

http://example.edu/bvl.P_Sel?facultyID=555

http://example.edu/bvl.P_Sel?facultyID=888

http://example.edu/bvl.P_Sel?facultyID=222

我尝试通过
file_get_contents("http://example.edu/bvl.P_Sel?facultyID=$lines[0]");获取内容

其中 $lines 是一个 ID 数组。 这将返回以下错误:

Warning: file_get_contents(http://example.edu/bvl.P_Sel?facultyID=222)    [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 

该 url 是一个示例,但是当我手动访问错误中的 url 时,它确实有效。如果我将 file_get_contents 变量替换为实际 ID,例如 ?facultyID=222,它会完美运行。

我访问了这个问题的答案 How to post data in PHP using file_get_contents? 并尝试将 $postdata 数组中的一个变量分配给一个变量,但我得到了相同的确切错误,只有从错误消息的 url 中删除了 ?facultyID=XXX

我对后者的实现是here

【问题讨论】:

  • print_r($lines) 显示什么?
  • 刚试过。出现相同的错误消息,并在错误消息的 URL 上附加了 id
  • 你在 php.ini 中有 allow_url_fopen = On 吗?
  • print_r($lines) 显示 Array ( [0] => 813667 [1] => 1124279 [2] => 760643 [3] => 668461 [4] => 2868 [5] => 33613 ) 哪些是正确的 ID
  • 好的,希望你能解决这个问题:-)

标签: php http post web-scraping file-get-contents


【解决方案1】:

当您使用 urlencode 函数 (%0D%0A) 时,那些编码字符是一个新行,因此您的 id 数组可能在每个元素中都有它们。试试这个:

// your code to generate the lines array
file_get_contents("http://example.edu/bvl.P_Sel?facultyID=" . trim($lines[0]));

【讨论】:

  • 我只是在努力使用 str_replace 来做到这一点,而那些换行符的东西仍然出现。谢谢,我喜欢stackoverflow,哈哈。
【解决方案2】:
$lines = array(813667,1124279,760643,668461,2868,33613);
print_r($lines);

输出:

Array ( [0] => 813667 [1] => 1124279 [2] => 760643 [3] => 668461 [4] => 2868 [5] => 33613 )

这个:

foreach($lines as $key => $value):
echo '<pre>';
print_r($lines[$key]);
endforeach;

输出:

    813667
1124279
760643
668461
2868
33613

还有这个: $get = file_get_contents("http://example.edu/bvl.P_Sel?facultyID=$lines[0]"); print_r($get);

输出:

  Example Domains
  As described in RFC 2606,
    we maintain a number of domains such as EXAMPLE.COM and EXAMPLE.ORG
    for documentation purposes. These domains may be used as illustrative
    examples in documents without prior coordination with us. They are 
    not available for registration.

怎么了? :) 这就是你需要的吗?

【讨论】:

  • 非常感谢您的帮助。我应该只给出我正在使用的直接链接。似乎它适用于 example.com,但不适用于我正在访问的实际域
【解决方案3】:

尝试使用 CURL 进行抓取和发布数据,因为它更强大、更高级。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2018-09-17
    • 1970-01-01
    • 2012-10-18
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多