对http请求使用php


Using php for http requests

我是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);

试试这个:

<?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.
?>

如果配置允许,您可以使用fopen,或者使用cURL或fsockopen函数来执行

您可以使用:

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

您不能使用file_get_contents吗?例如

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

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