Get article timestamp in PHP with Wikipedia API - php

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

Related

Correct Syntax to Pass Parameter from API to Function in PHP

I am 2 days into learning PHP and frustratingly I am struggling to GET and use a parameter passed into my API.
I have read the PHP $_GET documentation, it didn't take long, and also a number of SO pages about $_GET.
My use case is simple. I want to retrieve a list of records from MySQL db if they have a modified date greater than the passed in date. The function works if I hard code '2019-03-18 00:00:01' for example.
Using echo I can see I am getting the parameter.
In fact, copying the output from echo and using to update the function which I use in the argument returns the expected result.
I'm guessing this has been asked before but I can't find it. All the examples I read seem more challenging i.e. multiple variables or challenges with the function etc.
I must have made a newb mistake somewhere.
<?php
//Returns Lab Results Modified after the passed in date
include_once 'db_functions.php';
$db = new DB_Functions();
//Get JSON posted by Android Application
if (isset($_GET['date'])) {
$json = $_GET['date'];
echo $json;
// commenting out the next two line results in
// '2019-03-19 00:00:01' returning and not the json array.
$json = '2019-03-18 00:00:01';
echo $json;
$mod = $db->getLabResultsModifiedAfter($json);
$a = array();
$b = array();
if ($mod != false){
while ($row = mysqli_fetch_array($mod)) {
$b["ID"] = $row["ID"];
$b["last_modified"] = $row["last_modified"];
$b["LabRef"] = $row["LabRef"];
array_push($a,$b);
}
echo json_encode($a);
}
} else {
// Fallback behaviour goes here
}
?>
I haven't developed the app side function yet. I am using postman to pass in date of '2019-03-18 00:00:01' i.e. this for local.
Answer as provided by #aisby. I was using quotes in the passed in parameter.
The date you are passing in your URL does not following the format
'2019-03-18 00:00:01'. Try navigating to this URL ...
localhost:8080/its/… ... I have URL encoded the date 2019-03-18
00:00:01 in the querystring. I can see that you comment shows a date
query string starting with %27 which is the URL encoded single quote.
You should only send the value in query string variables. Not the
single or double quote string delimiters. – asiby 18 hours ago

Scraping data from php file

I am trying to get the car positions (if I can the cars state (gas, how clean, etc) from this site: https://carsharing.mvg-mobil.de/?ref=separate.
As far as I can tell they get their data from this URL:
https://carsharing.mvg-mobil.de/json/stations.php
Now I am having trouble converting that into usable XML format. I tried bringing it into String form by using
JSON.stringify()
and go from there but that didn't seem to work. What im having trouble with are the { and quotation marks
since your question is tagged as php, here is a simple code-snippet that will get you a xml-string:
<?php
//get json-string
$cars_json = file_get_contents("https://carsharing.mvg-mobil.de/json/stations.php");
//convert json to array
$cars_array = json_decode($cars_json,true);
//creat xml-object and fill recursive
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($cars_array, array ($xml, 'addChild'));
//create xml-string that can be saved
$cars_xmlstring = $xml->asXML();
echo $cars_xmlstring
?>

Problems parsing URL with JSON to FullCalendar

I'm trying to use the full calendar from www.fullcalendar.io passing a URL that returns a JSON formatted data:
[
{"id":"29041412","start":"2029-04-14T12:00","end":"2029-04-14T1:00","title":"Victor"},
{"id":"28041411","start":"2028-04-14T11:00","end":"2028-04-14T2030:00","title":"nani"},
{"id":"15051417","start":"2015-05-14T17:00","end":"2015-05-14T2029:00","title":"nani"},
{"id":"29041411","start":"2029-04-14T11:00","end":"2029-04-14T2016:00","title":"papapa"},
{"id":"30041411","start":"2030-04-14T11:00","end":"2030-04-14T2030:00","title":"baiak"},
{"id":"30041417","start":"2030-04-14T17:00","end":"2030-04-14T2031:00","title":"iepwpamxb"},
{"id":"15051412","start":"2015-05-14T12:00","end":"2015-05-14T2031:00","title":"lala"}
]
I try to follow and edit a demo that is inside the package of full calendar but it show example with json file, not with URL. I not find the solution for pass the URL that returns this data and the full calendar put events in the calendar.
I take format of my json from the json explained in the web.
this is my php code:
// Read and parse our events JSON file into an array of event data arrays.
$json = file_get_contents('http://***/diary_service_natursais.php?method=getEntireBooking');
$input_arrays = json_decode($json, true);
// Accumulate an output array of event data arrays.
$output_arrays = array();
foreach ($input_arrays as $array) {
// Convert the input array into a useful Event object
$event = new Event($array, $timezone);
// If the event is in-bounds, add it to the output
if ($event->isWithinDayRange($range_start, $range_end)) {
$output_arrays[] = $event->toArray();
}
}
First of all, you need to define Event object. You can try to include this file as follow:
require './utils.php';
then you need to define $range_start and $range_end variables with date format as yyyy-mm-dd
You can check this example.

How find Distance between two addresses through php

i am looking for some help to find the distance between two address through php
as i can not use the google maps api. so get a way from this post
Distance between two addresses
but i need to know how can send the request using URL pattern
and grab the repose to save them in database.
http://maps.google.com/maps/api/directions/xml?origin=550+Madison+Avenue,+New+York,+NY,+United+States&destination=881+7th+Avenue,+New+York,+NY,+United+States&sensor=false
thanks for any suggestion.
///////////////
After these answers i am there
$customer_address_url = urlencode($customer_address);
$merchant_address_url = urlencode($merchant_address);
$map_url = "http://maps.google.com/maps/api/directions/xml?origin=".$merchant_address_url."&destination=".$customer_address_url."&sensor=false";
$response_xml_data = file_get_contents($map_url);
$data = simplexml_load_string($response_xml_data);
XML response is visible when i put this url : http://maps.google.com/maps/api/directions/xml?origin=Quentin+Road+Brooklyn%2C+New+York%2C+11234+United+States&destination=550+Madison+Avenue+New+York%2C+New+York%2C+10001+United+States&sensor=false
but can not printing through
echo "<pre>"; print_r($data); exit;
You can try this..
$url = "http://maps.google.com/maps/api/directions/xml?origin=550+Madison+Avenue,+New+York,+NY,+United+States&destination=881+7th+Avenue,+New+York,+NY,+United+States&sensor=false";
$data = file_get_contents($url);
Now $data contains resulting xml data. You can parse this xml data using..
http://php.net/manual/simplexml.examples.php
use the haversine formula
Also check https://developers.google.com/maps/documentation/distancematrix/

Currency conversion JSON API parsing with PHP

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.

Categories