Could anyone help me parse this JSON API with PHP? I need to retrieve the currency exchange rate.
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%3D%22eurusd%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=cbfunc
At first you need to omit the last parameter in the URL, just remove &callback=cbfunc.
The PHP code to fetch the content is:
$rawData = file_get_contents("... your url ...");
$parsedData = json_decode($rawData);
$parsedData will now contain the content in a nested object structure.
Further info
You need fopen wrappers enabled for this to work. If they are not enabled, just use cURL to load the content from the page and put it into json_decode.
Here is a function that you can use to convert a currency to another currency using the respective 3 character currency codes (i.e. "USD" to "GBP").
<?php
function convertCurrencyUnit($from_Currency, $to_Currency, $unit_amount = 1) {
$url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%3D%22' . $from_Currency . $to_Currency . '%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
$rawdata = file_get_contents($url);
$decodedArray = json_decode($rawdata, true);
$converted_unit_amount = $decodedArray['query']['results']['rate']['Rate'];
return $converted_unit_amount * $unit_amount;
}
?>
For example, see the following simple call of this function.
<?php
echo convertCurrencyUnit("USD", "GBP"); //Prints "0.5953" to the browser. The current conversion rate from US Dollar to British Pound as of 04-16-2014.
?>
Also, you can pass an optional third parameter into the function to do a simple multiplication after the conversion is done.
Related
I am trying to make a basic PHP function in order to call json files repeatedly throughout the app. Every time I want to call a json file I use:
<? $site = json_decode(file_get_contents('views/partials/site.json')); ?>
Then I use echo to use data from json file like this:
<? echo $site[0]->title; ?>
But instead of repeating part one I want to write a function in the header and call it where I want to call a json file. After that i was planning to use the function like this:
$site = jsonCall('site');
by using the function below;
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
echo $jsonCalled;
};
but instead of what i want i got an array as a response from server. i think my function turns json file to an array and that way i can't call it properly.
anyone knows how to solve this simple issue? show me proper way to write this function so my code might look a bit easier to read. Thank you.
by changing echo in function with return and using jsonCall('site')[0]->title; everything worked fine.
Of course you are getting an array. Otherwise $site[0] (which is an array access at key zero) would not have worked.
From the PHP docs (http://php.net/manual/en/function.json-decode.php):
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
Your appropriate PHP type is array.
The following should work:
jsonCall('site')[0]->title;
Therefore I can not see a problem with your code?
The server is responding with Array because that is how PHP represents an array when you are echo'ing it. Your function should be returning the result.
Try:
function jsonCall($jsonurl){
// this is one line code. no difference from 3 lines below-> $jsonCalled = json_decode(file_get_contents($homepage . 'views/partials/' . $jsonurl . '.json'));
$url = $homepage . 'views/partials/' . $jsonurl . '.json';
$data = file_get_contents($url); // put the contents of the file into a variable
$jsonCalled = json_decode($data); // decode the JSON feed
// echo $jsonCalled;
return $jsonCalled; // <- this should work
};
I'm looking to get some input on how to make modular code that performs a PHP parse_ini_file and then uses the returned values to run JSON decodes.
I have a BACnet API that returns a JSON structure for BACnet points in an automation system. I wrote the following code to decode the JSON data to return just the "present-value" field and then I display the value on a webpage.
<?php
$url = "http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.0";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "<b>Room temperature</b>: ". $json_data["present-value"]. " DEG F";
;?>
This works well but I want to make this code modular so it can be used for many other points.
I created an INI file with a list of other points and the URL that contains the JSON data from the API.
## BACnet Configuration File
# BACnet Object URLs from WACNET Browser API
[bacnet]
SEA_RMT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.0
SEA_SRV_SEA_SV1_01_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.3
SEA_SRV_SEA_SV1_02_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.4
SEA_SRV_SEA_SV1_03_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.5
What I'd like to do is use the INI file to get the present value of each point in the list and then create a variable that is the name of the point and set it equal to the "present-value" field. Then I can reference the point using the PHP variable on the HTML page like this:
<?php echo "$SEA_SRV_SEA_SV1_01_EXHT";?>
I started with the code below but it doesn't work.
<?php
// Parse the settings file
$bacnetini = parse_ini_file('/var/www/config/bacnet.ini');
// Parse the keys to variables and add data
foreach ($bacnetini as $key => $value) {
$url = $value;
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$$key = $json_data;
}
?>
I'd love to get some other opinions on the best way to accomplish this since I don't really know where to go from here.
I've looked through these other Stack Overflow questions but I don't know how to get the pieces to all fit together.
Parsing a config file in php to variables
Get JSON object from URL
Why not try something like this instead? This will allow you to create other sections in your INI file that won't affect your script.
<?php
$bacnetini = parse_ini_file('/var/www/config/bacnet.ini', true);
$data = array();
foreach ($bacnetini['bacnet'] as $key => $url) {
$data[$key] = json_decode(file_get_contents($url), true);
}
var_dump($data['SEA_SRV_SEA_SV1_01_EXHT']);
?>
I need a simpler explanation than How do I extract data from JSON with PHP? And, I also need to spit the date away from the timestamp in the final PHP.
I can grab the "Test article" metadata in PHP via the Wikipedia JSON API this way:
<?php
$json_string = file_get_contents("https://en.wikipedia.org/w/api.php?action=query&titles=Test_article&prop=revisions&rvlimit=1&format=json");
print $json_string;
?>
Which gives me this:
{"continue":{"rvcontinue":"20161025140129|746140638","continue":"||"},"query":
{"normalized":[{"from":"Test_article","to":"Test article"}],"pages":{"29005947":
{"pageid":29005947,"ns":0,"title":"Test article","revisions":
[{"revid":746140679,"parentid":746140638,"user":"Theblackmidi72",
"timestamp":"2016-10-25T14:01:47Z","comment":"Undid revision 746140638 by
[[Special:Contributions/Theblackmidi72|Theblackmidi72]] ([[User
talk:Theblackmidi72|talk]])"}]}}}}
But how to I get and echo/print just the date from timestamp, i.e. the "2016-10-25" from "timestamp":"2016-10-25T14:01:47Z", and just that string from the whole JSON string?
I assume I need to first grab the full string 016-10-25T14:01:47Z and then strip the T14:01:47Z from it.
Edit 11/25/16 Jeff's answer works great, and I converted the function into a shortcode so I can insert it into post/page content.
function wikipedia_article_date() {
$url = "https://en.wikipedia.org/w/api.php?action=query&titles=Test_article&prop=revisions&rvlimit=1&format=json";
$data = json_decode(file_get_contents($url), true);
$date = $data['query']['pages']['746140638']['revisions'][0]['timestamp'];
$date = new DateTime($date);
return $date->format('m-d-Y');
}
add_shortcode('article_date','wikipedia_article_date');
But now I get a PHP Warning:
file_get_contents(https://en.wikipedia.org/w/api.php?action=query&
amp;titles=Test_article&prop=revisions&rvlimit=1&format=json):
failed to open stream: no suitable wrapper could be found in
/functions/shortcodes.php
is this an issue with my shortcode or with the original function?
json_decode converts JSON into a native PHP array for easy manipulation.
print_r will recursively print the array so that you can easily read it manually to discover the structure of the document.
DateTime::format is useful for converting date/time formats.
<?php
$url = "https://en.wikipedia.org/w/api.php?action=query&titles=Test_article&prop=revisions&rvlimit=1&format=json";
$data = json_decode(file_get_contents($url), true);
// this will show you the structure of the data
//print_r($data);
// just the value in which you're interested
$date = $data['query']['pages']['29005947']['revisions'][0]['timestamp'];
// cast to the format you want
$date = new DateTime($date);
echo $date->format('Y-m-d');
2016-10-25
Im new to php and tried to get a json object from the twitch API to retrieve one of its values and output it. i.e
i need to get the information from this link: https://api.twitch.tv/kraken/users/USERNAME/follows/channels/CHANNELSNAME
plus i need to to something so i can modify the urls USERNAME and CHANNELSUSERNAME. I want it to be a api to call for howlong user XY is following channelXY and this will be called using nightbots $customapi function.
the date i need from the json is "created_at"
Since we were able to clear out the errorsheres the final PHP file that works if anyone encounters similiar errors:
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
?>
You have a typo in your code on the first line and you're not storing the result of your json_decode anywhere.
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
You have to call the page this way page.php?username=yeroise&channel=ceratia in order to output the created_at value for this user and this channel.
In your code you're using 2 different ways to get the content of the page and you only need one (either file_get_contents or using CURL), I chose file_get_contents here as the other method adds complexity for no reason in this case.
I have an encoded string (it is too long to be posted here). When I use different utilities for decoding the string (http://www.the-art-of-web.com/javascript/escape/) the string looks perfect after urldecode(). However, when I actually pass the string through urldecode() in my php file on my testing environment the first 100 or so characters are missing. I cannot figure out why. I have tried both urldecode and rawurldecode. If you want to see the string I am trying to process you can make a GET request against this url http://pacific-wave-7885.herokuapp.com/api/opencart the string I am working with is the "contents" value of the JSON object
What i am trying to accomplish:
I want to make a php file that calls the above api address, gets the contents from the JSON object, decodes the string and parses the code.
here is what I have tried:
function utf8_urldecode($str) {
$str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
return html_entity_decode($str,null,'UTF-8');;
}
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('http://pacific-wave-7885.herokuapp.com/api/opencart', false, $context);
$contents_decode = utf8_urldecode($file);
echo $contents_decode;
You can see with this code that the "contents" starts with "language->load('shipping/usps')" and is missing the first 100 or so characters of that part of the string.
I have also tried this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://pacific-wave-7885.herokuapp.com/api/opencart");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$data = json_decode($output, true);
$contents = $data[0]['contents'];
$contents_decode = urldecode($contents);
echo $contents_decode;
curl_close($ch);
This also produces the same result - part of the beginning of the string is missing.
to reiterate: if you grab the encoded string straight from the JSON object and use an online decoding tool the string looks great, but once it is passed through urldecode() in my php file the first part of the string is missing characters.
If anyone can see what I am missing I would be so grateful.
Just fyi: My php environment is the latest version of XAMPP with php5 and the JSON object is coming from a NODE server with express.js.
If anyone has a better idea of how I can pass php code as a string from a Node server to a PHP server and then parse it I would be open to that as well.
I'm going to make two assumptions:
It's showing up starting at language->load('shipping/usps');
You are viewing the returned string in your browser.
Good news is that you aren't missing any characters! The browser is simply misinterpreting the tags -
<?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this->
The browser is trying to make sense of it - it doesn't know this is PHP, it thinks it is HTML. It sees < and thinks "oh cool, beginning of an HTML tag." And then it sees ? and it just tries to figure out what kind of malformed tag this is, and then it see's -> and it decides it must be an HTML comment, so it parses it as:
<!--?php
class ModelShippingUsps extends Model {
public function getQuote($address) {
$this--->
Change echo $contents_decode; to echo "<textarea>" . $contents_decode . "</textarea>" and you'll see the full string.
Why not just return the data (instead of a PHP block in the contents) and have your PHP class on the receiving end decode the JSON and complete the logic.
If you are insisting on getting the PHP block back...it might be easier to just return a JSON response from node/express and use json_decode to pull it into an array. In playing with this the only way I could make your PHP block JSON friendly was to escape it then encodeURIComponent.
<?php
$jsonString = '{
"name":"usps.php",
"version":1,
"platform":"opencart",
"contents":"%253C%253Fphp%250Aclass%2520ModelShippingUsps%2520extends...57D%250A%2509%2509%257D%250A%250A%2509%2509return%2520%2524method_data%253B%250A%2509%257D%250A%257D%250A%253F%253E",
"_id":"53c40942bddf820200000007",
"__v":0
}
';
$jsonArr = json_decode( $jsonString, true);
var_dump( urldecode( urldecode( $jsonArr["contents"] ) ) );
?>