So i'm trying to get location usng reverse geocoding
https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
so my question is (since i'm very new to php) how to get the result from URL into parameter (the result will be json encoded data)
you can use function file_get_contents to get Data from URL
$API_KEY ="XXXXXXX";
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=".$API_KEY;
$data = #file_get_contents($url);
$jsondata = json_decode($data,true);
if(is_array($jsondata) && $jsondata['status'] == "OK")
{
echo '<pre>'; print_r($jsondata);echo '</pre>';
}
To get the data we use the PHP curl functions.
[php]
// jSON URL which should be requested
$json_url = ‘www.yourdomain.com';
$username = ‘your_username'; // authentication
$password = ‘your_password'; // authentication
// jSON String for request
$json_string = ‘[your json string here]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . “:” . $password, // authentication
CURLOPT_HTTPHEADER => array(‘Content-type: application/json’) ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
[/php]
The result will be a jSON string.
Normally you have to send a jSON string to the jSON URL and you will get a jSON string back. To encode your data, just use the php jSON functions. Use json_encode to create a json string from your PHP array and use json_decode to transform the jSON string to PHP array.
Related
This is the function I use to grab a JSON file from Feedbin API.
<?php
error_reporting(E_ALL);
// JSON URL which should be requested
$json_url = 'https://api.feedbin.me/v2/entries.json';
$username = 'my_username'; // authentication
$password = ' my_password'; // authentication
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password // authentication
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting JSON result string
print_r ($result);
?>
Problem is the JSON I get is a bit.. strange.
It has a lot of chars like \u003E\u003C/a\u003E\u003C/p\u003E\n\u003Cp\u003E ...
You can see the JSON here.
When you call json_decode in PHP on strings that contain these encodings they will be correctly decoded. http://json.org/ lists \ufour-hex-digits as a valid character. There is no issue.
$ echo json_decode('"\u003E\u003C/a\u003E\u003C/p\u003E\n\u003Cp\u003E"');
></a></p>
<p>
They are valid unicode sequence. Here is a simple example
$data = array(
"abc" => 'åbcdéfg'
);
// Encode
$data = json_encode($data) . "\n";
// Output Value
echo $data;
// Output Decoded Value
print_r(json_decode($data));
Output
{"abc":"\u00e5bcd\u00e9fg"}
stdClass Object
(
[abc] => åbcdéfg
)
Hey I'm having some issues using cURL (I can't use file_get_contents because my web host won't allow it) to access parts of the wunderground weather api.
When I use the following code to access info on weather conditions I have no issues whatsoever:
<? $json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/geolookup/conditions
/q/IA/Cedar_Rapids.json';
// jSON String for request
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/geolookup/conditions
/q/IA/Cedar_Rapids.json]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$parsed_json = json_decode($result);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
However, when I make slight modifications in order to get data on high and low tides using the following code I get nothing:
<? $json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json';
// jSON String for request
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->{'date'}->{'pretty'};
echo "High tide is at ${tide_time} ";
?>
Now I know the issue may be that I'm dealing with an array in the second example but I'm not sure how to modify the code. I know that the record for the first low tide is [3] and I've tried making the following modification with no luck.
$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->[3]->{'date'}->{'pretty'};
echo "High tide is at ${tide_time} ";
Any help would be greatly appreciated!
The second parameter of json_decode allows you to decode the JSON into an array instead of an object. Try turning that on so you always know what you're dealing with:
$response = json_decode($result, true);
If that fails maybe you're not using the API correctly?
Not sure if anyone can help me out with a question.
I had to write some php for the company I work for that lets us integrate with an API that accepts a JSON body. I used the cUrl method, and the script is working great.
If I wanted to build another php page that would accept the request im sending, how would I go about this?
Say I wanted to allow someone to send this same request to me, and then wanted the info they sent to go into my database, how would turn their request into php strings?
Here is the code im sending.
<?
$json_string = json_encode(array("FirstName" => $name, "MiddleName" => " ", "LastName" => $last));;
// echo $json_string;
// jSON URL which should be requested
$json_url = 'http://www.exampleurl.com';
// jSON String for request
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array(
'Accept: application/json;charset=utf-8',
'Content-Type: application/json;charset=utf-8',
'Expect: 100-continue',
'Connection: Keep-Alive') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
echo $result;
$myArray = json_decode($result);
$action = $myArray->Action;
?>
To get the raw data from the POST that you would be receiving you would use $postData = file_get_contents('php://input');
http://php.net/manual/en/reserved.variables.post.php
Then you would json_decode() the contents of that POST back into JSON.
http://php.net/manual/en/function.json-decode.php
Not really good understood your question. May be you are looking for the way to read raw POST data? In that case open and read from php://stdin stream.
$stdin = fopen('php://stdin', 'r');
By the way read here ( http://php.net/manual/en/function.curl-setopt.php ) how to use CURLOPT_POSTFIELDS. This parameter can either be passed as a urlencoded string like 'para1=val1¶2=val2&...' or as an array with the field name as key and field data as value.
I'm trying to connect an API that uses 0AUTH2 via PHP. The original plan was to use client-side JS, but that isn't possible with 0AUTH2.
I'm simply trying get a share count from the API's endpoint which is here:
https://api.bufferapp.com/1/links/shares.json?url=[your-url-here]&access_token=[your-access-key-here]
I do have a proper access_token that I am using to access the json file, that is working fine.
This is the code I have currently written, but I'm not even sure I'm on the right track.
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[my-access-key-here]';
// JSON URL TO BE REQUESTED
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=http://bufferapp.com&access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
Like I said, I don't know if this is the best method - so I'm open to any suggestions.
I'm just trying to retrieve the share count with this PHP script, then with JS, spit out the share count where I need it on the page.
My apologies for wasting anyone's time. I have since been able to work this out. All the code is essentially the same - to test to see if you're getting the correct response, just print it to the page. Again, sorry to have wasted anyones time.
<?php
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[your_access_key_here]';
// URL TO RETRIEVE SHARE COUNT FROM
$url = '[your_url_here]';
// JSON URL TO BE REQUESTED - API ENDPOINT
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=' . $url . ' &access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
print $result;
?>
I am trying to figure out how I would go about caching the data I am pulling from a webservce json file onto my page so that I do not continually request this data and bring down the server.
I currently am pullin the json data like so:
// jSON URL which should be requested
$json_url = 'http://example.com/datastore.json?toolbar_id='.$persona['toolbar_id'].'';
// jSON String for request
$json_string = '[Json string? What is this]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$result = json_decode($result, true);
$result = $result[0];
From here I can pull the associative array results as I need them. But If I were to refresh the page, it would recall the server info. Any solutions?
You'd treat it like any other cache file:
Check if the cache file exists
If it does, check the filemtime() against the current time()
If it needs to be refreshed, make the cURL call and write the data to the cache file and carry on
If it does not need to be refreshed, simply return the data from the file to to your variable.
It will be the same JSON regardless if PHP returns it via cURL or if PHP returns it via fread() on a cache file.