0

So I've been stumped and I'm not sure how I would continue this as an example let's just use books.com as the URL and let's say the JSON response from the URL is

[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]

How would I print all of the titles (just the titles) without knowing exactly how many there are.

I know that I would need to loop through the JSON but I'm unsure how, if I could have any guidance that would be fantastic.

Tomasz
  • 4,847
  • 2
  • 32
  • 41
niro
  • 19
  • 2

2 Answers2

0

This key is to actually convert the JSON response into a PHP associative array by using json_decode and then loop through it.

// Convert the JSON into a PHP  associative Array 
$response = json_decode($curlResponse,true);

// Loop through the array
foreach ($response as $value) {
    echo $value['title'];
    echo '<br/>';
}
Hyder B.
  • 10,900
  • 5
  • 51
  • 60
0

You should get more familiar with json_decode() and foreach(). First you need to decode json (into array in this example) and then iterate through all elements.

Example of working code:

<?php

$json = '[{"title":"first_title","description":"second_title"},
{"title":"second_title","description":"second_description"}]';

$jsonArray = json_decode($json,true);

foreach($jsonArray as $entry) {
    echo $entry['title'].'<br>';    
}

Output:

first_title
second_title
Tomasz
  • 4,847
  • 2
  • 32
  • 41