reading json data from external url - php

$str = file_get_contents('http://uapi.alidays.it/service/2.0.0/rs/alidays/applications/fluidtravel/public/baskets/5660609ee4b0ab55863d6c42/contents/selected');
$json =json_decode($str,true);
echo '<pre>' . print_r($json,true) . '</pre>';
foreach($json['data'] as $item['value']['baskettile']) {
echo $item['value']['baskettile']['type'];
echo '<br>';
}
i tried to access the data like this but it says Warning: Invalid argument supplied for foreach()

The value of baskettile is an object with properties like type and status.
It is not an array. It doesn't make sense to iterate over it with foreach(... in ...).
Just access the values directly.
$json['data']['0']['value']['baskettile']['type']

You need to debug your code. Chances are $item is not what you think it is.
The quickest way is to do a var_dump($item) in your foreach. From there you will see that the variable either is not an array or the key does not exist.

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

PHP Array inside of an array issue

I'm having some problems getting the data through my PHP loop.
<?php
$url = 'https://www.fibalivestats.com/data/1653309/data.json';
$content = file_get_contents($url);
$json = json_decode($content, true);
?>
<?php
foreach($json['totallds']['sPoints'] as $item); {
echo $item;
}
?>
The error I'm getting is an array to string conversion error. What I'm trying to get is the data from the sPoints array that will give me a Top 5 points scorers for a basketball game.
I'll build a table for this in HTML later but for now, it's not displaying the data at all and I'm getting errors. I feel like I may have confused arrays and strings too. Any thoughts about what I'm doing wrong? JSON file can be found in the $url variable.
Also if it helps, here's the link to where I have gotten the data from and what context the Top 5 is from https://www.fibalivestats.com/u/NSS/1653309/lds.html
Thanks!
Your $item is an array, so you can't just echo it like that. You can, however, echo its columns, for example:
foreach($json['totallds']['sPoints'] as $item) {
echo $item['firstName'] . ' ' . $item['familyName'];
}
Notice the removed semicolon between the foreach () and {.
Well, array to string conversion error means you're trying to echo an array.
If you see the return of the url you are looking at, you can verify that the "sPoints" key returns an array with several objects.
Try to change echo to print_r or var_dump to view entire data or complete your business logic.
Try changing:
echo $item;
to:
var_dump($item);

counting data in a multidemensional array

I upload several files with Zend and want to count the $data array to get the filenames.
$data = array_merge_recursive(
$this->getRequest()->getPost()->toArray(),
$this->getRequest()->getFiles()->toArray()
);
I found this code for counting in another post
array_sum(array_map("count", $data))-1;
It gives the right amount of pieces and I can get the names, but it also gives a warning:
Warning: count(): Parameter must be an array or an object that
implements Countable
I tried to give the other dimensions like:
array_sum(array_map("count", $data['fieldname']))-1;
But like expected, it doesn't work.
Any help appreciated! The only question is how to get the amount of given filenames.
***edit regarding to the answer I post a screenshot how the $data array looks like, which is correct
And here what the statement with the warning counts (of course 1 is to subtract). Perhaps there is an other possibility to count.
So everything might be nice, but I want to get rid of the warning.
Judging by the added screenshot of the $data array, shouldn't you be doing this the below?
count($data['PAD_Document_Path'])
Get specific filenames by looping like so
foreach($data['PAD_Document_Path'] as $key => $value) {
$name = pathinfo($value)['filename'];
// do stuff with name
}
See pathinfo. From that docs page:
Example #1 pathinfo() Example
<?php
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
?>
The above example will output:
/www/htdocs/inc
lib.inc.php
php
lib.inc

Read nested json in php

I know others have already asked about this, but I don't find a solution for my problem. In my PHP page I call an external service and I can't modify the response obtained.
I'm moving my first steps both with JSON and PHP.
The response is a JSON like this, I print this using the var_dump method:
object(stdClass)#1 (3)
{
["search_string"]=>string(15) "ABCDEFG HI LMNO"
["resut"]=>string(5) "apixi"
["0"]=>array(1){
[0]=>object(stdClass)#2(2){
["resp_code"]=>string(7) "12.34.0"
["resp_description"]=>string(15) "ABCDEFG HI LMNO"
}
}
}
In my PHP page I can read the value ”ABCDEFG HI LMNO” for the key "search_string" with this code, in the $output variable I store the result of the cUrl call
.......
$output = curl_exec($ch);
$jsonDecode =json_decode(str_replace('""','"',$output));
var_dump($jsonDecode);
echo $jsonDecode -> search_string;
I need the str_replace method because the JSON is dirty but not always, how can I access at the fields "resp_code" and "resp_description" and then store them in a variable? I tried many solutions but none works for me.
Instead of converting JSON array to stdClass object you can also convert it to regular PHP array by adding second parameter to the json_decode function:
$jsonDecode =json_decode(str_replace('""','"',$output), true);
In your case in the output, you'll get a multidimensional array.
Then, to access resp_code and resp_description, you can do something like this:
$respCode = $jsonDecode[0]["resp_code"];
$respDescription = $jsonDecode[0]["resp_description"];
In the decoded JSON you have, the resp_code and resp_description keys are difficult to get to, because the top-level object has a numerical ("0") attribute. Trying to reach that attribute like this:
$jsonDecode -> 0
will give this parsing error:
syntax error, unexpected '0' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'
Trying the same with a string notation (-> "0") also fails.
However, the suggestion in the error message is useful: encapsulate the zero with braces. Then you can proceed easily by adding the array index selector ([0]) to get to the object and keys of your interest, like this:
echo $jsonDecode->{0}[0]->resp_code;
echo $jsonDecode->{0}[0]->resp_description;
If you expect more elements in that array $jsonDecode->{0}, then loop over them like this:
foreach ($jsonDecode->{0} as $element) {
echo $element->resp_code;
echo $element->resp_description;
}
Alternative
If, however, you prefer to work with associative arrays instead of objects, you can use the second argument of json_encode as stated in the docs:
assoc
When TRUE, returned objects will be converted into associative arrays.
So then you would pass true as second argument:
$jsonDecode = json_decode(str_replace('""', '"', $output), true);
The above code would then be rewritten like this to access the variable as an associative array:
foreach ($jsonDecode[0] as $element) {
echo $element["resp_code"];
echo $element["resp_description"];
}

Error when accessing array in JSON object

I've been looking all over for the solution to this problem, but everything I try always returns the same error.
Fatal error: Cannot use object of type stdClass as array
This is the JSON resource I'm trying to access with PHP cURL:
https://www.easports.com/iframe/fifa16proclubs/api/platforms/PS4/clubs/36881/members
The issue I'm having is accessing the raw array. I've had success using the following code with objects, but I always have trouble when there is an array involved.
$phpObj = json_decode($json);
if (!is_null($phpObj->raw))
{
$object = $phpObj->raw;
foreach ($object as $obj)
{
echo "<tr id='clubs-search-result'><td class='club-search-name'>" . $obj->name . "</td><td class='blaze-id hidden'>" . $obj->blazeId . "</td><td><button type='button' class='form-button players-search-button red-bg'>Select</button></td></tr>";
}
}
I know that this is not the correct way to access an array, which is what I need help with. I want to be able to access the raw array and then iterate through all the objects inside the array. I've looked at many code examples but nothing seems to be working for my scenario.
The above code works with this resource:
http://www.easports.com/iframe/fifa16proclubs/api/platforms/PS4/clubsComplete/United
Only because I'm accessing nested objects and there are no arrays [] involved.
Any help would be appreciated. Thanks!
It appears the foreach loop needs to run on the first (and only) array in $phpObj->raw.
You need to change the foreach to:
foreach ($object[0] as $obj)

Categories