I can't change JSON into a PHP array - php

For some strange reason I can't change the following JSON to a PHP array:
{"sides0":{"name_nl":"Voorkant100","name":"Frontside100","template_overlay":""},"sides1":{"name_nl":"Achterkant100","name":"Backside100","template_overlay":"1"}}
I've validated the json and it's valid.
First I post $product['sides'] to my page, containing:
"{\"sides0\":{\"name_nl\":\"Voorkant100\",\"name\":\"Frontside100\",\"template_overlay\":\"\"},\"sides1\":{\"name_nl\":\"Achterkant100\",\"name\":\"Backside100\",\"template_overlay\":\"1\"}}"
Then I use json_decode on it like this:
$sidearr = json_decode($product['sides'], true);
If I then do:
echo '<pre>';
print_r($sidearr);
echo '</pre>';
It prints the first part of my question.
Now I want to loop over it, but even this test shows nothing:
foreach($sidearr as $side){
echo 'test';
}
I tried testing if it even is an array with:
echo is_array($sidearr) ? 'Array' : 'not an Array';
echo "\n";
And it shows me that it is not an array. Why is that? I always thought using json_decode on a json string and add true inside the function turns it into a PHP array.

It prints the first part of my question.
Because $sidearr is a string now, decode it again, you'll get an array.
$sidearr = json_decode($sidearr, true);

Related

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

PHP Using ($_GET['url']) and then displaying that json data?

<?php
function get_stuff()
{
($_GET['http://****RemovedForSecurityPurposes****.repairshopr.com/api/v1/tickets?api_key=****RemovedForSecurityPurposes****']);
echo $_GET;
}
get_stuff();
?> /* Yes, Pointless closing tag, I'm cool like that. */
For some reason when I run this code the output I'm getting is "Array" and I can't figure out why? I know it is an array that I'm getting from the URL but I thought it would just print in whatever format its in? Am I missing something?
Thanks In advance!
You cannot pass website URL to $_GET.
You should use file_get_contents()
$content = file_get_contents('http://YOUR_URL');
If you have valid json then you can convert it to an array.
$data = json_decode($content, true);
then print it,
echo '<pre>'; print_r($data);
The Message of OP when I run this code the output I'm getting is
"Array".
You need to use file_get_contents to read a file from a remote server. If your file response an array then you have to use print_r or var_export or var_dump. Or if your file response is a string(json) then you need to store it in a variable and apply a decode method.
function get_stuff(){
$response = file_get_contents('http://****RemovedForSecurityPurposes****.repairshopr.com/api/v1/tickets?api_key=****RemovedForSecurityPurposes****');
print_r($response); // if array
$arr = json_decode($response); // decode of json
print_r($arr);
}
get_stuff();
I think you will understand what i mean. Let me know if you are useful or need some help.

parsing a json array does not give me the values

below is my 'script.json' file with json array and i want the values of webUserid and webPassword
{
"totalSize":2,
"webUserId":"abc",
"webPassword":"def",
"operation":"send",
"testMode":true,
"records":[
{
"phoneNumber":"1908908399",
"message":"Happy Birthday",
"Id":"a0YL0000008QYunMAG",
"deviceId":"ABCDEFXABCDEF"
}
]
}
I tried below one but not getting the result
<?php
$jsonString=file_get_contents("script.json");
$decoded=json_decode($jsonString,true);
foreach($decoded->data as $name){
echo $name->totalSize;
}
?>
Zarif, try the below code, its working 100%......... :)
<?php
$jsonString=file_get_contents("script.json");
$decoded=array(json_decode($jsonString,true));
foreach($decoded as $name){
echo $name['totalSize'];
}
?>
There's no need for a foreach loop in your current example, as you only have one level.
Your main problem is you're trying to use the result of your json_decode as an object when you've previously stated you want the result as an associative array.
The 2nd param of json_decode specifies what format the return value is in, so as you've done
$decoded = json_decode($jsonString, true);
you'll receive an array, which you could access like
echo $decoded['totalSize'];
if you wanted to treat it as on object as you've done in your question, either state false or omit a 2nd param in json_decode (it's false by default anyway), and that'll let you do what you're trying to do:
$decoded = json_decode($jsonString);
$decoded->totalSize;
lets say that
$myJSON = yourPostedJSON.
$myJSON = json_decode($myJSON, true);
echo $myJSON['webUserId'];
echo $myJSON['webPassword'];

unable to read json objects in php

I want to read JSON in php:
$productsArr = json_decode(stripslashes($_GET['object'])); //this give me word Array
stripslashes($_GET['object']) //gives me [{"code":"44-3"}]
echo $productsArr->{'code'}; //gives me nothing
I even tried this:
foreach($productsArr as $article)
{
echo $article->code; //nothing is echoing
}
How to access the JSON formatted data in a loop?
1) Force an array to be returned by supplied true to second argument of json_decode.
2) Ensure that this produces an array:
$productsArr = json_decode(stripslashes($_GET['object']), true);
print_r($productsArr);
Assuming it does. Access your elements as such:
echo $productsArr['foo']['bar'];

Help Decoding JSON

I'm trying to get the "screenshotUrls" string from this piece of json:
$request_url = 'http://itunes.apple.com/search?term=ibooks&country=us&entity=software&limit=1';
$json = file_get_contents($request_url);
$decode = json_decode($json, true);
echo $decode['results'][0]['screenshotUrls'];
But I get only text "Array"
What have I done wrong?
Try
var_dump($decode['results'][0]['screenshotUrls']);
IF you get 'Array' output by PHP that means that you're trying to echo an actual array (or the string 'Array'...). That means you need to get a specific index value.
Since $decode['results']['0']['screenshotUrls'] is an array, if you want just a string (say, delimited by commas), you could use
echo implode(",", $decode['results']['0']['screenshotUrls']);
This will iterate over the array, and return a comma-separated string of all the URLs.
Do a var_dump($decode['results']['0']['screenshotUrls']). You'll find that the ['screenshotUrls'] is actually an Array, containing one or more URLs (hence the plural 'urls' in its name).
There's nothing wrong with your code so far, but $decode['results'][0]['screenshotUrls'] is an array of all the URLs to screenshots. To go through each one individualy, you need to do:
forearch ($decode['results'][0]['screenshotUrls'] as $url) {
// Do stuff here
}

Categories