How to decode Json data from php file into another php file? - php

I am new in Creating API`s and I have created 2 files.php
1- API_ReadAll.php ( Its an API code that after execution will return Json Result)
Example Execute the below link:
http://localhost:8080/To%20work%20on/API_FUNCTIONS/API_ReadAll.php
Output:
Status Data Records:
[
{
STATUS_ID: "14",
STATUS_CODE: "AP 2013",
STATUS_DESCRIPTION: "Amazing wheel"
}, {
STATUS_ID: "13",
STATUS_CODE: "AP55.0",
STATUS_DESCRIPTION: "A23 Powder"
}, {
STATUS_ID: "16",
STATUS_CODE: "AP525.0",
STATUS_DESCRIPTION: "Power Drink"
}
]
2- Index.php ( Its an php file consist of HTML elements and table to display the data retrieved from the the page above)
I have tried to do the below:
// path to your JSON file
$url = 'http://localhost:8080/To%20work%20on/API_FUNCTIONS/API_ReadAll.php';
$json = file_get_contents($url);
$data = json_decode($json,true);
echo $data->STATUS_ID;
foreach($data As $display){
echo $display->STATUS_ID."<br>";
echo $display->STATUS_CODE."<br>";
echo $display->STATUS_DESCRIPTION."<br>";
}
Output:
Warning: file_get_contents( http://localhost:8080/To%20work%20on/API_FUNCTIONS/API_ReadAll.php): failed to open stream: No such file or directory in C:\xampp\htdocs\To work on\Temp-Builder\SEED_STATUS.PHP on line 122
Notice: Trying to get property 'STATUS_ID' of non-object in C:\xampp\htdocs\To work on\Temp-Builder\SEED_STATUS.PHP on line 125
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\To work on\Temp-Builder\SEED_STATUS.PHP on line 125
Question:
How can I get and fetch the above Json inside the Index.php.

I'd first of all recommend you to read through the following guide create simple rest api with php (or any other tutorial of your choice), to get into the field of REST Apis with php.
Rather than handling api endpoints as file, you can use curl to perform a request against them. The result of that request can then be decoded to json with php's build in json_decode function.
To get you a starting point, I applied your approach to the curl sample found on php.net:
// define api endpoint
$url = 'http://localhost:8080/To%20work%20on/API_FUNCTIONS/API_ReadAll.php';
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$json_obj = json_decode($output)
I also noticed, that you're passing "true" as second parameter to json_decode(). That way you will receive an associative array rather than an object. But in your example you're treating it as an object.
Also be aware of the fact that localhost is only accessable within your local network. So the community here cannot acess your example if that was your intension.
Good luck
-------------------------------------------------------------------------
Thank you for your time:
Regarding the link you provided to me to learn more about how to build the API. I did learn and build my API`s from that link and I successfully achieved what I am looking for.
Second about the code the comment of the link yes sure it will only have access from local serve, and I just posted like that trying to figure if this was a right way or not.
Regarding the code, I just tried your`s and still not working showing the following error:
Notice: Trying to get property 'STATUS_CODE' of non-object in C:\xampp\htdocs\To work on\Temp-Builder\INDEX.PHP....
Code:
// define api endpoint
$url = 'http://localhost:8080/To%20work%20on/Temp-Builder/API_FUNCTIONS/API_ReadAllSeed_Status.php';
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, $url);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$json_obj = json_decode($output);
foreach ($json_obj as $display){
echo $display->STATUS_ID."<br>";
echo $display->STATUS_CODE."<br>";
echo $display->STATUS_DESCRIPTION."<br>";
}

Related

how to get unknown string in $_GET method through URL

I want to pass a string from one PHP file to another using $_GET method. This string has different value each time it is being passed. As I understand, you pass GET parameters over a URL and you have to explicitly tell what the parameter is. What if you want to return whatever the string value is from providing server to server requesting it? I want to pass in json data format. Additionally how do I send it as Ajax?
Server (get.php):
<?php
$tagID = '123456'; //this is different every time
$tag = array('tagID' => $_GET['tagID']);
echo json_encode($tag);
?>
Server (rec.php):
<?php
$url = "http://192.168.12.169/RFID2/get.php?tagID=".$tagID;
$json = file_get_contents($url);
#var_dump($json);
$data = json_decode($json);
#var_dump($data);
echo $data;
?>
If I understand correctly, you want to get the tagID from the server? You can simply pass a 'request' parameter to the server that tells the server what to return.
EDIT: This really isn't the proper way to implement an API (like, at all), but for the sake of answering your question, this is how:
Server
switch($_GET['request']) {
case 'tagID';
echo json_encode($tag);
break;
}
You can now get the tagID with a URL like 192.168.12.169/get.php?request=tagId
Client (PHP with CURL)
When it comes to the client it gets a bit more complicated. You mention AJAX, but that will only work for JavaScript. Your php file can't use AJAX, you'll have to use cURL.
$request = "?request=tagID";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '192.168.12.169/get.php' . $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
$content = trim(curl_exec($ch));
curl_close($ch);
echo $content;
EDIT: added the working cURL example just for completeness.
Included cURL example from: How to switch from POST to GET in PHP CURL
Client (Javascript with AJAX)
$.get("192.168.12.169/get.php?request=tagId", function(data) {
alert(data);
});

cURL using info from mySQL, then storing the cURL'ed info

I'm programming in PHP.
An article I've found useful until now was mainly about how to CURL through one site with a lot of information, but what I really need is how to cURL on multiple sites with not so much information - a few lines, as a matter of fact!
Another part is, the article focus is mainly at storing it at the FTP server in a txt file, but I have loaded around 900 addresses into mysql, and want to load them from there, and enrich the table with the information stored in the links - Which I will provided beneath!
We have some open public libraries with addresses and information about these and an API.
Link to the main site:
The function I would like to use: http://dawa.aws.dk/adresser/autocomplete?q=
SQL Structure:
Data example: http://i.imgur.com/jP1J26U.jpg
fx this addresse: Dornen 2 6715 Esbjerg N (called AdrName in databasen).
http://dawa.aws.dk/adresser/autocomplete?q=Dornen%202%206715%20Esbjerg%20N
This will give me the following output (which I want to store in the AdrID in the database):
[
{
"tekst": "Dornen 2, Tarp, 6715 Esbjerg N",
"adresse": {
"id": "0a3f50b8-d085-32b8-e044-0003ba298018",
"href": "http://dawa.aws.dk/adresser/0a3f50b8-d085-32b8-e044-0003ba298018",
"vejnavn": "Dornen",
"husnr": "2",
"etage": null,
"dør": null,
"supplerendebynavn": "Tarp",
"postnr": "6715",
"postnrnavn": "Esbjerg N"
}
}
]
How to store it all in a blob, as seen in the SQL structure?
If you want to make a cURL request in php use this method
function curl_download($Url){
// is cURL installed yet?
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
// OK cool - then let's create a new cURL resource handle
$ch = curl_init();
// Now set some options (most are optional)
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $Url);
// Set a referer
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
And then you call it using
print curl_download('http://dawa.aws.dk/adresser/autocomplete?q=Melvej');
Or you can directly convert it jSON object
$jsonString=curl_download('http://dawa.aws.dk/adresser/autocomplete?q=Melvej');
var_dump(json_decode($jsonString));
The data you download is json, so you can store that in a varchar column rather than blog.
Also the site with the api does not seem bothered about http referrer, user agent etc so you can use file_get_contents in place of curl.
So simply get all the results from your db, iterate over them, making a call to the api, and update the appropriate row with the correct data:
//get all the rows from your database
$addresses = DB::exec('SELECT * FROM addresses'); //i dont know how you actually access your db, this is just an example
foreach($addresses as $address){
$searchTerm = $address['AdrName'];
$addressId = $address['Vid'];
//download the json
$apidata = file_get_contents('http://dawa.aws.dk/adresser/autocomplete?q=' . urlencode($searchTerm));
//save back to db
DB::exec('UPDATE addresses SET status=? WHERE id=?', [$apidata, $searchTerm]);
//if you want to access the data, you can use json_decode:
$data = json_decode($apidata);
echo $data[0]->tekst; //outputs Dornen 2, Tarp, 6715 Esbjerg N
}

Parsing json data using php from youtube data api v3

I am using Youtube data api v3 to retrieve data for search query using the below url
https://www.googleapis.com/youtube/v3/search?part=snippet&q=text&key=apikey&maxResults=25.
I am getting json response, while i am using json decode to parse the json data, i am getting empty result, can any one tell me how to retrieve the data
I am using below php code to parse
$videourl="https://www.googleapis.com/youtube/v3/search?part=snippet&q=hello&key=apikey&maxResults=25";
$json = file_get_contents($videourl);
$data = json_decode($json,true);
print_r($data);
obtaining the json response from the below url:
https://www.googleapis.com/youtube/v3/search?part=snippet&q=hello&key=apikey&maxResults=25
if (extension_loaded('curl')) {
# create a new cURL resource
$ch = curl_init();
# set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://googleapis.com/.....");
curl_setopt($ch, CURLOPT_HEADER, 0);
# Setting cURL's option to return the webpage data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
# grab URL and pass it to the browser
if($json = curl_exec($ch)) {
if(!($data = #json_decode($json)) instanceof stdClass) {
trigger_error('Unable to decode json. '. print_r(error_get_last(), true));
}
}
else trigger_error('CUrl Error:'.curl_error($ch));
# close cURL resource, and free up system resources
curl_close($ch);
}
else trigger_error('CUrl unsupported', E_USER_WARNING);
You should test the return value of file_get_contents. Be careful that this function will return FALSE in case of error (and not NULL). So you should test the return value with === FALSE in order to not be confused by empty values.
In your case, if you are trying to access the exact url that you posted in your question, google is returning a code 400 (bad request), this is why you get a return of FALSE.

Getting JSON Object by calling a URL with parameters in PHP

I'm trying to get json data by calling moodle url:
https://<moodledomain>/login/token.php?username=test1&password=Test1&service=moodle_mobile_app
the response format of moodle system is like this:
{"token":"a2063623aa3244a19101e28644ad3004"}
The result I tried to process with PHP:
if ( isset($_POST['username']) && isset($_POST['password']) ){
// test1 Test1
// request for a 'token' via moodle url
$json_url = "https://<moodledomain>/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$obj = json_decode($json_url);
print $obj->{'token'}; // should print the value of 'token'
} else {
echo "Username or Password was wrong, please try again!";
}
Result is: undefined
Now the question:
How can I process the json response format of moodle system? Any idea would be great.
[UPDATE]:
I have used another approach via curl and changed in php.ini following lines: *extension=php_openssl.dll*, *allow_url_include = On*, but now there is an error: Notice: Trying to get property of non-object. Here is the updated code:
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$moodle = "https://<moodledomain>/moodle/login/token.php?username=".$_POST['username']."&password=".$_POST['password']."&service=moodle_mobile_app";
$result = curl($moodle);
echo $result->{"token"}; // print the value of 'token'
Can anyone advise me?
json_decode() expects a string, not a URL. You're trying to decode that url (and json_decode() will NOT do an http request to fetch the url's contents for you).
You have to fetch the json data yourself:
$json = file_get_contents('http://...'); // this WILL do an http request for you
$data = json_decode($json);
echo $data->{'token'};

Callback from API not happening after posting parameters to API URL from server side

API integration description
The API needs a form to be posted to the API URL with some input fields and a customer token. The API processes and then posts response to a callback.php file on my server. I can access the posted vals using $_POST in that file. That's all about the existing method and it works fine.
Requirement
To hide the customer token value from being seen from client side. So I started with sending server side post request.
Problem
I tried with many options but the callback is not happening -
1) CURL method
$ch = curl_init(API_URL);
$encoded = '';
$_postArray['customer_token'] = API_CUSTOMER_TOKEN;
foreach($_postArray as $name => $value)
{
$encoded .= urlencode($name).'='.urlencode($value).'&';
}
// chop off last ampersand
$encoded = substr($encoded, 0, strlen($encoded)-1);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
$resp echoes 1 if the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); is removed but the callback does not happen. I am setting a session variable in the callback script to verify.Is it needed that the API be synchronous in order to use curl method, so that curl_exec returns the response?
2) without CURL as given in Posting parameters to a url using the POST method without using a form
But the callback is not happening.
I tried with the following code too, but looks like my pecl is not installed properly because the HttpRequest() is not defined.
$req = new HttpRequest($apiUrl, HttpRequest::METH_POST);
$req->addQueryData($params);
try
{
$r->send();
if ($r->getResponseCode() == 200)
{
echo "success";
// success!
}
else
{
echo "failure";
// got to the API, the API returned perhaps a RESTful response code like 404
}
}
catch (HttpException $ex)
{
// couldn't get to the API (probably)
}
Please help me out! I just need to easily send a server side post request and get the response in the callback file.
Try to debug your request using the curl_get_info() function:
$header = curl_getinfo($ch);
print_r($header);
Your request might be OK but it my result in an error 404.
EDIT: If you want to perform a post request, add this to your code:
curl_setopt($ch, CURLOPT_POST, true);
EDIT: Something else I mentioned at your code: You used a '1' at the 'CURLOPT_RETURNTRANSFER' but is should be 'true':
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
At least this is how I usually do it, and you never know if the function will also understand a '1' as 'true';
EDIT: The real problem: I copy-pasted your source and used it on one of my pages getting this error:
Warning: urlencode() expects parameter 1 to be string, array given in C:\xampp\htdocs\phptests\test.php on line 8
The error is in this line:
foreach($_postArray as $name => $value)
$_postArray is an array with one value holding the other values and you need either another foreach or you simple use this:
foreach($_postArray['customer_token'] as $name => $value)
As discussed in the previous question, the callback is an entirely separate thing from your request. The callback also will not have your session variables, because the remote API is acting as the client to the callback script and has its own session.
You should really show some API documentation here. Maybe we're misunderstanding each other but as far as I can see, what you are trying to do (get the callback value in the initial CURL request) is futile, and doesn't become any less futile by asking twice.

Categories