Using php for http requests - php

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

You may use fopen if config allows, or cURL or fsockopen functions to do that

You could use:
$json_str = file_get_contents($url);
$json = json_decode($json_str, true);

Couldn't you use file_get_contents? E.g.
<?php
$url = "YOUR_URL";
$json = file_get_contents($url);
// handle the data
$data = json_decode($json, TRUE);
var_dump($data); // example
?>

If you are doing a lot of requests you can try using a http class like Buzz which will Help clean up your code https://github.com/kriswallsmith/Buzz

Related

Returning value from restAPI in php, echo value not showing

I'm trying to return a value from my API using PHP, api can be found here:
code is as follows:
Im not seeing the echo on my page, don't see any errors and I believing im reading the json in correctly. Any help appreciated!
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue["Age"];
?>
From what I can tell, the json is not valid on the server side (due to the "connected to db" text in front of the {} part). I think it would be a good idea to fix the server side response json data, if possible!
For now, here is a way to get the value it looks like you are intending to retrieve:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$adjusted_response = str_replace('connected to db', '', $response);
$returnvalue = json_decode($adjusted_response, true);
echo $returnvalue['tv_shows']['Age'];
?>
Output:
$ php example.php
16+
If the server side json data is fixed, I think you could shorten the code to something like this:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue['tv_shows']['Age'];
?>
The thing is that $response is returned as string , in order to fix that you need to edit your backend and make it give the response without "connected to db"

How to Json In PHP 'iyas'

http://simsimi.com/getRealtimeReq?uuid=VbQqwsQ3qiCw1T04VrrFQzBBlkfZibg3YFkbWz6VquZ&lc=id&ft=1&reqText=Eh+jelek&status=W
How to get value from respSentence
Im using php lang ^_^
" {"status":200,"respSentence" 11 \:"respSentence"}"` is not valid json. Use some online sites to validate your json and try like this,
$json = '{"status":200,"respSentence" :"iyas"}';
$array = json_decode($json, true);
echo $array ['respSentence'];
You can try using file_get_contents and json_decode PHP functions
$url = "http://simsimi.com/........";
$data = file_get_contents($url);
$json = json_decode($data, true);
echo $json ['respSentence'];
hope it helps

get Specific JSON Response Value

json response as below:
{"Success":true,"ErrorCode":0,"UserInformation":{"UserID":"19"}......
how do I get the UserID value by using json_decode?
I tried the below code with no luck.
$Response = json_decode($Response[2]);
echo $Response[0][0][0];
This should work:
<?php
$json = '{"Success":true, "ErrorCode":"0","UserInformation":{"UserID":"19"}}';
$response = json_decode($json, true);
echo $userId = $response["UserInformation"]["UserID"];
?>
Please check the PHP documentation of json_decode at http://php.net/json_decode
You can use object as well if you skip the second parameter of the json_decode function.

get data from JSON file (with cURL)

I would like to trnsform some JSON data to a php array, this is my code:
<?php
$obj1=json_decode('http://ddragon.leagueoflegends.com/cdn/3.15.5/data/en_US/champion/Aatrox.json', true);
$championname = $obj1[data][aatrox][name];
echo $championname;
?>
The problem is that i don't know how to get the data from http://ddragon.leagueoflegends.com/cdn/3.15.5/data/en_US/champion/Aatrox.json
How can i make this code work?
Try with file_get_contents() like this:
$json = file_get_contents('http://ddragon.leagueoflegends.com/cdn/3.15.5/data/en_US/champion/Aatrox.json');
$obj1 = json_decode($json , true);
$championname = $obj1['data']['aatrox']['name'];
echo $championname;
Use file_get_contents to download a file.
$json = file_get_contents('http://ddragon.leagueoflegends.com/cdn/3.15.5/data/en_US/champion/Aatrox.json');
$obj1 = json_decode($json, true);

Unable to get json in correct format with file_get_contents()

I parse a parameter to a php file and try to get json with file_get_contents().
This is my Code:
< ?php
$url = $_GET['url'];
$url = urldecode($url);
$json = file_get_contents($url, true);
echo($json);
? >
This is the called URL:
http://vimeo.com/api/v2/channel/photographyschool/videos.json
This is a part of my result:
[{"id":40573637,"title":"All For Nothing - \"Dead To Me\" & \"Twisted Tongues\""}]
And so on... So everything is escaped. There are even \n in the result.
Since I neet to work afterwards with the json (in js), I need a non escaped version!
Interesting thing is, that my code works for example with this json:
http://xkcd.com/847/info.0.json
What is my problem?
If you just want to proxy/forward the response then just echo it as it is with the correct Content-Type header:
<?php
header('Content-Type: application/json');
$json = file_get_contents('http://vimeo.com/api/v2/channel/photographyschool/videos.json');
echo $json;
?>
Tho you have to be very wary of the url passed as it could cause XSS!
And as the API is slow/resource hungry you should cache the result or at least save it in a session so its not repeated on each page load.
<?php
$cache = './vimeoCache.json';
$url = 'http://vimeo.com/api/v2/channel/photographyschool/videos.json';
//Set the correct header
header('Content-Type: application/json');
// If a cache file exists, and it is newer than 1 hour, use it
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
echo file_get_contents($cache);
}else{
//Grab content and overwrite cache file
$jsonData = file_get_contents($url);
file_put_contents($cache,$jsonData);
echo $jsonData;
}
?>
Use this:
echo json_decode($json);
EDIT: FORGET the above. Try adding:
header('Content-Type: text/plain');
above
$url = $_GET['url'];
and see if that helps.
You should use json_decode :
http://php.net/manual/en/function.json-decode.php
better yet, where you deliver your json use:
json_encode(array(
"id" => 40573637,
"title" => 'All For Nothing - "Dead To Me" & "Twisted Tongues"'
));

Categories