【问题标题】:Using php for http requests使用 php 处理 http 请求
【发布时间】:2012-09-03 07:07:15
【问题描述】:

我对 PHP 非常陌生,需要使用 HTTP 请求来下载我服务器外部的 URL。该 URL 是一个 PHP 函数,它返回我已解码的 JSON 代码。有什么建议吗?

我已经尝试过基本代码:

    <?php   
    //Code for forming the url (which I'm sure is correct)
    $url = ...
    $response = fopen($url,"x+");
    $response = json_decode($response);
    echo $response;
    ?>
    //javascript in a seperate file that calls the php code
    var response = xmlhttp.responseText;
alert(response);

【问题讨论】:

  • 你试过什么?你能发布一些代码并清楚你需要什么吗?您的问题中没有任何我们可以为您提供建议的内容...
  • 将外部 uri 写入正文中的 json
  • 注意,fopenfile_get_contents 以及其他用于处理 文件 的函数,只有在 @987654324 时才能工作@ 在您的 PHP 配置中启用。
  • @Sam:是的,默认开启。但出于安全原因,偏执的管理员经常禁用它。 (如果脚本过于幼稚并盲目地使用用户输入来构建路径,则很容易被欺骗执行任意远程内容。)

标签: php http httprequest


【解决方案1】:

试试这个:

<?php
$url = 'YOUR_URL_HERE';

$data = file_get_contents( $url ); // it is a JSON response as per your statement.

$data= json_decode($data);
print_r($data); // now, it's a normal array.
?>

【讨论】:

  • 评论时记住“//” ;)
【解决方案2】:

如果配置允许,您可以使用 fopen,或者使用 cURL 或 fsockopen 函数来做到这一点

【讨论】:

  • 我试过 fopen 但没有用。我的 php 代码是通过 ajax 调用的。它构建 URL(我已多次检查其正确性),然后使用 url 作为第一个参数和 w+ 作为第二个参数调用 fopen(我只是认为我需要读/写功能)。然后,我使用 echo 将响应传递回我的 ajax 函数,在那里我使用 xmlhttp.responseText 和警报打印出结果。
【解决方案3】:

你可以使用:

$json_str = file_get_contents($url);
$json = json_decode($json_str, true);

【讨论】:

    【解决方案4】:

    你不能使用 file_get_contents 吗?例如

    <?php
    
    $url = "YOUR_URL";
    $json = file_get_contents($url);
    
    // handle the data
    $data = json_decode($json, TRUE);
    
        var_dump($data); // example
    ?>
    

    【讨论】:

      【解决方案5】:

      如果你有很多请求,你可以尝试使用像 Buzz 这样的 http 类,这将有助于清理你的代码 https://github.com/kriswallsmith/Buzz

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-09
        • 1970-01-01
        • 1970-01-01
        • 2010-12-08
        • 2019-04-16
        相关资源
        最近更新 更多