-1

I have a PHP script that retrieves the JSON result from the Wikipedia API and stores it in $json variable, then I json decode it into $data:

<?php

$q = htmlspecialchars(($_GET["q"]));

$url = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srnamespace=0&srprop=snippet&format=json&callback=json&origin=*&prop=links|extracts|categories|images&srsearch=test';
$json = file_get_contents($url);

/*
print "<pre>";print_r($json);print "</pre>";
*/

$data = json_decode($json,true);
echo $data['query']['search'][0]['title'];

This retrieves the JSON file, but I am not able to work with it. I need to extract the Title tag and echoing it like this doesn't do anything.

echo $data['query']['search'][0]['title'];

Any idea how to correct my code to retrieve the following title tag:

enter image description here

jjj
  • 2,594
  • 7
  • 36
  • 57
  • 1
    Possible duplicate of [How can I parse a JSON file with PHP?](https://stackoverflow.com/questions/4343596/how-can-i-parse-a-json-file-with-php) – Adam Oct 26 '18 at 19:26
  • That looks like it should've worked. – Don't Panic Oct 26 '18 at 19:33
  • Exactly, I can't find what's wrong with the test. I've spent an hour on it already and I am just not getting it. – jjj Oct 26 '18 at 19:38

1 Answers1

3

Remove &callback=json from your URL. That's making a request for JSONP (ironic link to wikipedia). It wraps the response with a JavaScript callback function, so instead of just JSON you need in PHP, you're getting

/**/json(THE JSON HERE)

You can see it in the page source, even if it displays as JSON on the page. Those extra characters are making json_decode fail. That parameter is intended more for cross-domain requests from JS.

It looks like you're already accessing the resulting array properly with

echo $data['query']['search'][0]['title'];

You might think it would give you some kind of warning or notice when you try to access those array keys when $data is null, but it won't.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • The JSON callback is for if you're making a cross domain request (it wraps the response with the callback function). Useful from within a client browser, but generally not needed for PHP API calls. – circusdei Oct 26 '18 at 19:40
  • @circusdei Yes, I was just reading about that. I'm usually working on the PHP side, so wasn't familiar with it – Don't Panic Oct 26 '18 at 19:42
  • I'll remove if you want to incorporate into your response :) – circusdei Oct 26 '18 at 19:43
  • @circusdei it's JSONP, isn't it? Just making sure I'll be referring to the right thing – Don't Panic Oct 26 '18 at 19:43
  • this is awesome, worked like a charm... I know one thing... it would take me forever to figure out without your help... you've really made my day – jjj Oct 26 '18 at 19:44
  • @Don'tPanic JSONP it is. – circusdei Oct 26 '18 at 19:44