繁体   English   中英

使用php进行HTTP请求

[英]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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM