Parse the data from Google Place api response in (Json format) - php

How am i suppose to store the Hotel name and location from the response provided by google place api in PHP array. If my search string is restaurant in New York.
The response of the api is in json format.
My script for sending the search request is:
<?php
if(isset($_GET['text']))
{
if(!empty($_GET['text']))
{
$search_text=strip_tags($_GET['text']);
$hostname = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=$search_text&sensor=true&key=AIzaSyDVdJtIAvhmHE7e2zoxA_Y9qWRpp6eE2o8";
// read the post from PayPal system and add 'cmd'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$hostname");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$res = curl_exec($ch);
curl_close($ch);
if(!$res)
{
// error log
echo'Unable to find results.';
} else {
**// ALL output printing code goes down here**
//$res=json_decode($res);
//var_dump(json_decode($res));
$obj=var_dump(json_decode($res, true));
print_r($obj['"results']);
}
} else {
echo'<h4><font color="red">Please enter the text to search.</font></h4>';
}
}
?>
Well, the output of the above code is something in json format. But i need to retrieve the Name of the Restaurant and their location from the json output.
So, Please suggest me a way to extract the exact output.

As I can see the results key contains arrays with the data you need.
Just do something like:
$jsonContent = json_decode($res, true);
foreach ($jsonContent['results'] as $result) {
// now you have the $result array that contains the location of the place
// and the name ($result['formatted_address'], $result['name']) and other data.
}
I hope you know what to do from this point.

Related

Pass PHP variable/value from one page to another

I have been trying to send the xml response I have stored in '$kxml' variable to the 'kycresult.php' page. I want to fetch the values from that xml and just print it. I am able to fetch the values if I store the xml in txt file and then get it using 'simplexml_load_file' but I don't want to create an extra file. Please let me know if there is a way to send the $kxml on next page.
$kycch = curl_init();
curl_setopt($kycch, CURLOPT_URL, $csckua_url);
curl_setopt($kycch, CURLOPT_POSTFIELDS, $kycxml);
curl_setopt($kycch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($kycch, CURLOPT_TIMEOUT, 20);
$kycresult = curl_exec($kycch);
$curl_errno = curl_errno($kycch);
$curl_error = curl_error($kycch);
curl_close($kycch);
// echo $kycresult;
$kxml = simplexml_load_string($kycresult);
if ($kxml['ret'] == 'Y') {
// $ksuccess = 'Authentication Successful';
header('location:Kycresult.php');
} else {
$ksuccess = 'Authentication Failed';
}
As one of the possible solutions you can store the variable in session
session_start();
$_SESSION['kxml'] = $kxml;
Then on the next page it will be available through
$kxml = $_SESSION['kxml'];
But actually it still stores in the auxiliary file by default under the hood.

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'};

codeigniter - proper way to return data from API

I'm trying to create an API.
I have a controller that does something, and returns let's say "ABC" as a string.
my url looks like this:
http://myserver/myapp/myAPImethod/parm1
inside the method, I have code like this:
header ('Content-Type: application/json; charset=UTF-8');
$model= str_replace("%snv%"," ",$model);
echo json_encode($model);
The application that consumes this API has a controller that does the following:
public function curl($url){
//echo 'in the routine';
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data=curl_exec($ch);
print_r($data);
curl_close($ch);
return $data;
}
$url = "http://myserver/myapp/index.php/myAPImethod/hname";
$jsondata = $this->curl($url);
//print_r(json_decode($jsondata));
My question is this: When I run the application that consumes my API, because I have an echo statement, it shows "ABC" on the page. But I don't want it to display the results. I just want it to pass the data to the consuming application. I've tried changing the echo statement in the API method to a "return" statement, but I don't get any data sent over to the caller.
Thanks.
Create a JSON view and pass data to the json view
// In view create a file json_view.php and paste this content
// RFC4627-compliant header
header('Content-type: application/json');
// Encode data
if(isset($response)) {
echo json_encode($response);
}
else
echo json_encode(array('error' => true));
And in your controller
// Build our view's data object
$data = array('response' => $response_data);
// Load the JSON view
$this->load->view('json_view', $data);

Accessing JS data from PHP

A remote site is supplying a data structure in a js file.
I can include this file in my page to access the data and display it in my page.
<head>
<script type="text/javascript" src="http://www.example.co.uk/includes/js/data.js"></script>
</head>
Does anyone know how I use PHP to take this data and store in it a database?
You should GET that file directly, via, for example, CURL. Then parse it, if it comes in JSON, you can use json-decode.
Simple example (slightly modified version of code found here):
<?php
$url = "http://www.example.co.uk/includes/js/data.js";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
...
$output = curl_exec($ch);
$info = curl_getinfo($ch);
if ($output === false || $info['http_code'] != 200) {
$error = "No cURL data returned for $url [". $info['http_code']. "]";
if (curl_error($ch))
$error .= "\n". curl_error($ch);
}
else {
$js_data = json_decode($output);
// 'OK' status; save $class members in the database, or the $output directly,
// depending on what you want to actually do.
...
}
//Display $error or do something about it
?>
You can grab the file via CURL or some other HTTP downloading library/function. Then, parse the data. If you're lucky, the data is in a JSON format and you can use a PHP function to convert it into a PHP array. Then, iterate through the items in the array, inserting each into your database.

Categories