BlueDogRanch BlueDogRanch - 26 days ago 9
JSON Question

Get article timestamp in PHP with Wikipedia API

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.

Answer
  1. json_decode converts JSON into a native PHP array for easy manipulation.

  2. print_r will recursively print the array so that you can easily read it manually to discover the structure of the document.

  3. 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

Comments