phparraysjsondecodesafe-browsing

echo results from an google safe browsing api array


I know this is a basic question, but I cannot figure out how to actually do this. I have read countless tutorials about it but they seemingly do not work.

var_dump($google_check);

returns the following:

string(488) "{
  "matches": [
    {
      "threatType": "MALWARE",
      "platformType": "LINUX",
      "threat": {
        "url": "http://malware.testing.google.test/testing/malware/"
      },
      "cacheDuration": "300s",
      "threatEntryType": "URL"
    },
    {
      "threatType": "MALWARE",
      "platformType": "LINUX",
      "threat": {
        "url": "http://malware.testing.google.test/testing/malware/"
      },
      "cacheDuration": "300s",
      "threatEntryType": "URL"
    } 
  ]
} 
"

I want to echo results from the array, so something like

echo $google_check[0][matches][threat];
echo $google_check[1][matches][threat];

Problem is this returns illegal offset on matches and threat, and only echo's a single character {

What am I doing wrong? How do I echo the results from this array without dumping the entire array?


Solution

  • The response you recieved is in json so you'll need to first json_decode the response.

    $decoded = json_decode($google_check, true);
    

    Then you can access it like an array

    echo $decoded['matches'][0]['threat'];
    echo $decoded['matches'][1]['threat'];
    

    if you want the url value you'll need to do it like this.

    echo $decoded['matches'][0]['threat']['url'];
    echo $decoded['matches'][1]['threat']['url'];
    

    please also note, when looking at array keys that aren't numerical you'll need to wrap in quotes (e.g. $decoded['matches'] instead of $decoded[matches]).

    Here's a quick explanation on json

    https://www.tutorialspoint.com/json/json_php_example.htm