Reputation: 574
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?
Upvotes: 0
Views: 756
Reputation: 40861
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
Upvotes: 4