Parsing JSON from a URL (PHP CURL) [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
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.

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

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/>';
}

Related

Extracting data from multiple Nested Json using PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 1 year ago.
Here's the json
{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}
Here's my code
$json = json_decode($data);
foreach($json["result"] as $result){
foreach($result["files"] as $file){
echo $file["file_code"];
}
}
I want to extract all values from the "file_code". I got an error
Warning: Invalid argument supplied for foreach()
I was able get the VALUE of the first one using
echo $json->result->files[0]->file_code;
Is it possible to use a LOOP for the files[0]?
This line:
foreach($json["result"] as $result){
sees $json['result'] as an object, and so the next line tests for total_pages["files"], which doesn't exist.
Putting both foreach's together solves the problem:
$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}}';
$json = json_decode($data, true);
foreach($json["result"]["files"] as $file)
print $file["file_code"];
Teh playground
Alternatively, make the JSON result into an array, and use object property accessors instead of associative array bindings.
$data='{"msg":"OK","server_time":"2021-11-19 16:41:22","status":200,"result":[{"total_pages":1,"files":[{"download_url":"DOWNLOADLINKHERE1","single_img":"IMAGEURLHERE1","file_code":"CODEHERE1","title":"TITLEHERE1"},{"download_url":"DOWNLOADLINKHERE2","single_img":"IMAGEURLHERE2","file_code":"CODEHERE2","title":"TITLEHERE2"}],"results_total":"2","results":2}]}';
$json = json_decode($data);
foreach($json->result as $result){
foreach($result->files as $file){
echo $file->file_code;
}
}
Teh playground
I replicated your situation and it turns out that your JSON is invalid. You're missing a } at the end.
The reason for not getting an exception is because json_decode does not throw an error by default. You can make it do so by adding the JSON_THROW_ON_ERROR flag,
read the docs for more info.
This works perfect for me. If you have any thoughts please feel free to correct me.
$num = count($json->result->files);
echo $num;
for($i=0;$i<$num;$i++)
{
echo $json->result->files[$i]->file_code;
}

How to dynamically insert JSON data into a PHP array for foreach [duplicate]

This question already has answers here:
How to create a JSON object
(5 answers)
Closed 3 years ago.
I have the following PHP code, which gets executed when I hit the Submit button in a form:
// Save data
if(isset($_POST['save'])){
$newDataArr = array();
foreach ($data_array[0] as $k=>$v){
$newDataArr[] = array($k => $_POST[$k]);
}// ./ foreach
echo json_encode($newDataArr);
}
The echo I get is the following:
[{"ID->id":"esKZSCDfIC"},{"DT->createdAt":"2020-01-26T13:02:42"},{"DT->updatedAt":"2020-01-26T13:02:42"},{"ST->aString":"hey1"},{"NU->number":123},{"GPS->coords":["2.2222","44.4444"]},{"BL->aBool":false},{"AR->theArray":["xx","ww"]},{"FL->theFile":"https:\/\/xscoder.com\/xserver\/uploads\/6dydDtoTt5JjZzFc5L5V_image.jpg"},{"PO->userPointer":"vbN3b0C7bC"}]
Then I'll have to add that array into my JSON file as it follows:
$data = json_encode(array_values($newDataArr), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
file_put_contents('Test.json', $data);
But of course the syntax of my $newDataArr is not the right one, each JSON object must not be inside the { }, so this:
{"ID->id":"esKZSCDfIC"},
must become:
"ID->id":"esKZSCDfIC",
Is there a way to dynamically create a valid JSON array and push it to my Test.json file?
I've been through many posts on StackOverflow, but the result I get is always the same. I must use the PHP code above to get keys and values from my HTML inputs.
Instead of creating and pushing a new array on each iteration, set the values this way:
$newDataArr[$k] = $_POST[$k];
Hope this helps.

Cannot loop through items in JSON (php) [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
i have the following Json sent via ajax to test.php:
[{},{"product[]":"john","qty[]":"12","price[]":"100","total[]":"1200"},{"product[]":"juan","qty[]":"22","price[]":"3.5","total[]":"77"},{"product[]":"louis","qty[]":"99","price[]":"1.22","total[]":"120.78"},{"product[]":"paul","qty[]":"5","price[]":"2.1","total[]":"10.5"},{"product[]":"carl","qty[]":"9","price[]":"14","total[]":"126"},{"total_amount":"1533.00"}]
In my php file I am trying to loop through each individual product[], qty[], price[] and list values:
<?php
$obj = json_decode($_POST["mydata"]);
header('Content-Type: application/json');
// echo json_encode($obj[1]->{'product[]'}); //(works)
foreach($obj as $item) {
echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';
}
?>
but this throws an error.
What is wrong in my loop?
There are a couple of things wrong with the code, the first is that you decode as objects and try and use this as an array. You need to pass true as the second parameter to json_decode() to make it an associative array.
The second is that your array contains elements which don't have all of the details. The last element only has "total_amount", so none of the other fields exist. This is why I use
if ( isset($item['product[]'])){
to check the object before outputting the data...
$obj = json_decode($_POST["mydata"], true);
header('Content-Type: application/json');
foreach($obj as $item) {
if ( isset($item['product[]'])){
echo $item['product[]'].'<br>';
echo $item['price[]'].'<br>';
echo $item['qty[]'].'<br>';
echo $item['total[]'].'<br>';
}
}
Pass true as second argument to json_decode.
Per the documentation:
assoc
When TRUE, returned objects will be converted into associative arrays.
So your code becomes:
$obj = json_decode($_POST["mydata"], true);
Also note that the first entry in your array is empty, so you're gonna have to check for that.

How to get Json Objects inside the Json Array and store it in MySql In php [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I want get Json objects from the json array and store each values in mysql using php.
$arr = "[{"fruit":"Apples","isSelected":false,"number":0},{"fruit":"Oranges","isSelected":false,"number":0},{"fruit":"Potatoes","isSelected":false,"number":0},{"fruit":"Tomatoes","isSelected":false,"number":0},{"fruit":"Grapes","isSelected":false,"number":0},{"fruit":"Dhanana","isSelected":false,"number":0}]";
try this code
Using json_decode
<?php
$arr = '[{"fruit":"Apples","isSelected":false,"number":0},{"fruit":"Oranges","isSelected":false,"number":0},{"fruit":"Potatoes","isSelected":false,"number":0},{"fruit":"Tomatoes","isSelected":false,"number":0},{"fruit":"Grapes","isSelected":false,"number":0},{"fruit":"Dhanana","isSelected":false,"number":0}]';
$data = json_decode($arr);
echo "<pre>";
print_r($data);
foreach($data as $k=>$v){
echo $v->fruit." ".$v->isSelected." ".$v->number."<br>"; //store in db here using value
print_r($v);
}
?>

How can i Iterate through data returned in Ajax success? [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
How can I iterate to get id value? This is my array:
[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]
tried
<?php
foreach($faculty as $value)
{
echo $value['Id'];
}
?>
Gives an error
Use of undefined constant Id - assumed Id
This is a json which is basically a string, to be more precise the given json contains a list (currently 1 element):
[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]
You need to convert it to an array first:
$jsonValues = json_decode($json, true); //here you will have an array of users (1 now)
foreach($jsonValues as $faculty) //for each user do something
{
echo $faculty['Id'];
}
This is JSON format. First you have to decode it. Example:
$a = '[{"email_id":"gayatri.dsf#detedu.org","Id":"216"}]';
$dec = json_decode($a);
echo $dec[0]->Id;
Result: 216
Decoded you have an array, containing exactly one object. You have to access the object properties with -> then.
With JSON [] brackets means an array, while {} brackets mean objects. Learn more: https://en.wikipedia.org/wiki/JSON

Categories