Search code examples
phpapi

Response from api seems to be a string - how to iterate it?


I'm receiving data from a webservice in this format - yes, the variable var visual is included:

var visual = {
    "status": "ok",
    "cached": "1",
    "cache_time": "1674481162",
    "photos": [{
        "photo_id": "81517195",
        "title": "title 1"
    }, {
        "photo_id": "79383391",
        "title": "Title 2"
    }]
}

See the response here. I guess it's not valid json - I seem to receive it as a string. How can I convert it into json so that I can iterate over each "photos" node with php?


Solution

  • You can use the php function json_decode. Even tough your code looks like it was written in javascript, if you had the same code as a PHP variable called as $visual (with it containing the string, as you mentioned), the solution would look something like this:

    $visual = "...";  // the response in string format
    $decodedJSON = json_decode($visual, true)  // $decodedJSON will contain the provided json in an associative array (specified by the second param)
    $firstPhoto = $decodedJSON["photos"][0];  // getting the first photo
    

    You can find more information in the documentation.

    EDIT: as @MerlinDenker mentioned above, if you get the var visual = ... with your response, then you just have to remove it from the beginning of your response (it can be done using substr() for example), and then pass it to the json_decode as a string.