BlueDogRanch BlueDogRanch - 6 months ago 34
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:

$json_string = file_get_contents("");
print $json_string;

Which gives me this:

{"normalized":[{"from":"Test_article","to":"Test article"}],"pages":{"29005947":
{"pageid":29005947,"ns":0,"title":"Test article","revisions":
"timestamp":"2016-10-25T14:01:47Z","comment":"Undid revision 746140638 by
[[Special:Contributions/Theblackmidi72|Theblackmidi72]] ([[User

But how to I get and echo/print just the date from timestamp, i.e. the "2016-10-25" from
, and just that string from the whole JSON string?

I assume I need to first grab the full string
and then strip the
from it.

  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.


$url = "";

$data = json_decode(file_get_contents($url), true);

// this will show you the structure of the 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');