简体   繁体   中英

Using php for http requests

I am very new to PHP, and need to use an HTTP Request to download a URL that is external to my server. That URL is a PHP function that returns JSON code which I have decode. Any suggestions?

I have tried basic code:

    <?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);

Try this:

<?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函数来执行此操作

You could use:

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

Couldn't you use file_get_contents? Eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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