1

I'm new to PHP and I'm trying to use it to filter information from the New York Times' article search API. I'm still struggling to figure out how I can pull out the "web-url" and "snippet" from the JSON response even after looking through this similar question. I'm using json_decode to turn the response into an associative array. Here's my code

   $data = file_get_contents($queryURL);
    $jsondata = json_decode($data, true);
    if (count($jsondata) != 0) 
    {
        foreach($jsondata['response']as $key => $value) 
        {
          echo "Key: " . $key . " Value: " . $value . " <br>";
        } 
    }

This only prints out the words "array", "ok" and "copyright".

Here's a sample of the json:

"response": {
    "meta": {
        "hits": 25,
        "time": 332,
        "offset": 0
    },
    "docs": [
        {
            "web_url": "http://thecaucus.blogs.nytimes.com/2012/01/01/virginia-attorney-general-backs-off-ballot-proposal/",
            "snippet": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
            "lead_paragraph": "DES MOINES -- Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
            "abstract": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
            "print_page": null,
            "blog": [ ],
            "source": "The New York Times",
            "multimedia": [ ],
            "headline": {
                "main": "Virginia Attorney General Backs Off Ballot Proposal",
                "kicker": "The Caucus"
            },
Community
  • 1
  • 1
user2466886
  • 205
  • 1
  • 3
  • 14
  • `foreach($jsondata['response']['docs'] as $value){ echo $value['web_url'; echo $value['snippet']; }`? – Sean May 19 '15 at 04:52

2 Answers2

4

Try this. You need to loop through each of the docs

foreach ($jsondata['response']['docs'] as $doc) {
    echo "web_url: " . $doc['web_url'] . " snippet: " . $doc['snippet'];
}
GeorgeQ
  • 1,382
  • 10
  • 8
2

When you are looping through $jsondata['response']

then when your $key is meta (Similarly for other keys as well like docs etc) its $value is an array i.e

array(
"hits"=> 25,
        "time"=> 332,
        "offset"=> 0
)

So when you are trying to echo this $value it prints array as its a property of echo in php to print arrays as string "array".

I hope this makes clear what you are doing wrong!!!


You might need to do something like this

foreach($jsondata['response']as $key => $value) 
        {
          // check if $jsondata['response'][$key] is an array using is_array()
          // handle as per array

        } 

Learn about is_array

Let me see
  • 5,063
  • 9
  • 34
  • 47