【问题标题】:php file_get_contents giving errorphp file_get_contents 给出错误
【发布时间】:2012-04-28 16:43:06
【问题描述】:

当我在浏览器上运行以下查询时:

http://127.0.0.1:8096/solr/select/?q=june 17&start=0&rows=8&indent=on&hl=on&hl.fl=Data&wt=json

我得到了结果。没问题。请注意,在 6 月和 17 日之间有一个空格

但是,当我在我的 PHP 中收到该查询时,即 $q=June 17 我使用

$url="http://127.0.0.1:8096/solr/select/?q=$q&start=0&rows=8&indent=on&hl=on&hl.fl=Data&wt=json";
$json_O=json_decode(file_get_contents($url),true);

在此之后,我在我的萤火虫上看到以下内容:

<b>Warning</b>:  file_get_contents(http://127.0.0.1:8096/solr/select/?q=june 17&amp;start=0&amp;rows=8&amp;indent=on&amp;hl=on&amp;hl.fl=Data&amp;wt=json) [<a href='function.file-get-contents'>function.file-get-contents</a>]: failed to open stream: HTTP request failed! HTTP/1.1 505 HTTP Version Not Supported

但是请注意,如果我的查询词之间没有空格(我的意思是如果它是一个词),那么一切都是完美的。

为什么当我在浏览器上发出与 file_get_contents() 完全相同的查询时它可以正常工作。任何解决方案将不胜感激。

【问题讨论】:

    标签: php json http


    【解决方案1】:

    q 参数值中有一个空格。可能是这样。尝试urlencode()ing 参数。

    $url="http://127.0.0.1:8096/solr/select/?q=".urlencode($q)."&start=0&rows=8&indent=on&hl=on&hl.fl=Data&wt=json";
    
    $json_O=json_decode(file_get_contents($url),true);
    

    【讨论】:

    • 谢谢纳德。我正在使用 urlencode,但可能不在正确的位置。您的代码 sn-p 有效。非常感谢。
    【解决方案2】:

    这是因为file_get_contents函数通过HTTP向Web服务器发送请求,看起来像这样

    GET /solr/select/?q=bla HTTP/1.0
    Host: 127.0.0.1
    ...[more headers here]...
    

    请注意,请求中指定了 in HTTP 版本 (HTTP/1.0)

    现在,如果您的请求字符串中有空格,您可以发送类似的内容

    GET /solr/select/?q=bla foo HTTP/1.0
    Host: 127.0.0.1
    ...[more headers here]...
    

    您的服务器似乎将foo 解析为版本并返回505 HTTP Version Not Supported。如果您对字符串中的空格进行编码(例如,将其替换为 %20,则不会发生这种情况)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 2018-03-24
      • 2017-09-30
      • 1970-01-01
      相关资源
      最近更新 更多