Q: illegal string offset JSON -> PHP - php

I already view a lot of questions in stackoverflow about my problem, but I didn't find any solution. I don't know where is the problem in my code? I got illegal string offset message at this row:
echo $value["country"] . ", " . $value["competition"] . "<br>";
My full code:
<?php
// file_get_contents call instead
$str = file_get_contents('general.json');
$json = json_decode($str,true);
foreach($json as $key => $value){
echo $value["country"] . ", " . $value["competition"] . "<br>";
}
?>
my json source sample:
["{\"country\":\"America\",\"competition\":\"Copa America\",\"club\":\"BOCA JUNIORS\"}","{\"country\":\"Germany\",\"competition\":\"Bundesliga\",\"club\":\"HANNOVER\"}","{\"country\":\"Asia\",\"competition\":\"JLeague\",\"club\":\"NAGOYA\"}"]
If I view format of the data with var_dump($json) then I see it is an Array. With var_dump($value) then I see there is a string. Please help for me where is the problem in my code, why could not echo value country and value competition?

The problem is that you have json that has been encoded twice, both the array and the elements in the array.
You should avoid doing that, but if you cannot change the source, you need to decode the values as well:
<?php
// file_get_contents call instead
$str = file_get_contents('general.json');
$json = json_decode($str,true);
foreach($json as $key => $value){
// decode the $value string
$value = json_decode($value, true);
echo $value["country"] . ", " . $value["competition"] . "<br>";
}
?>
An example.

Related

How do I get one json value value each?

in this my php code
echo $_POST[result];
in this my php result
{
"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}
I want to print out each value one by one. What should I do?
json_decode Parsing JSON
<?php
$str = '{"result_code":0,
"err_cd":"",
"result_msg":"",
"store_id":"M20C2685",
"status":"APPROVED",
"order_no":"600a2a044c9be",
"tr_no":725,
"tr_price":1000,
"pay_price":1000,
"approved_day":"20210122",
"approved_time":"102744",
"param1":"",
"param2":""
}';
$arr = json_decode($str, true);
echo $arr['err_cd'] . PHP_EOL;
echo $arr['result_msg'] . PHP_EOL;
echo $arr['store_id'] . PHP_EOL;
echo $arr['status'] . PHP_EOL;
// ......
// Circulates each value in the array
foreach ($arr as $item) {
echo $item . PHP_EOL;
}

Loop through associative array and assign values

I have an array:
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
What I want is to loop through this array, which I have done, but I am now confused because I don't know how to get the output I desire.
foreach ($array as $key => $value) {
//echo $key . "\n";
foreach ($value as $sub_key => $sub_val) {
if (is_array($sub_val)) {
//echo $sub_key . " : \n";
foreach ($sub_val as $k => $v) {
echo "\t" .$k . " = " . $v . "\n";
}
} else {
echo $sub_key . " = " . $sub_val . "\n";
}
}
}
The above code loops through the array, but this line of code:
echo $sub_key . " = " . $sub_val . "\n";
gives me:
step_no = 1 description = Ensure that you have sufficient balance step_no = 2 description = Approve the request sent to your phone
when I change it to:
echo $sub_val . "\n";
it gives me:
1 Ensure that you have sufficient balance 2 Approve the request sent to your phone
But I what I truly want is:
1. Ensure that you have sufficient balance
2. Approve the request sent to your phone
Is this possible at all? Thanks.
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction) {
echo $instruction['step_no'] . '. ' . $instruction['description'] . "\n";
}
If it's HTML you may want to use <ol> and <li>.
It smells like you are not running this script in command line but in browser. If so, then \n makes no visual effect (unless within <pre> block) and you u must use HTML tag <br /> instead. Also, drop concatenation madness and use variable substitution:
echo "{$sub_key}. = {$sub_val}<br/>";
You can simple achieve this way
<?php
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction){
echo $instruction['step_no'].'. '.$instruction['description'].PHP_EOL;
}
?>
Alway keep it simple.

how to get value of id and name from json response

I want to get value of id and name from the string given below in php. Can any body help me please.
string(35400) "{"cities":[{"id":"3279","name":"Narasaraopet"},{"id":"1852","name":"Srirangapatna"}
That's not really a valid json (missing ]} at the end), but assuming you removed something from it just to post the question, do it like this:
$json = '{"cities":[{"id":"3279","name":"Narasaraopet"},{"id":"1852","name":"Srirangapatna"}]}';
$decoded = json_decode($json, true);
foreach($decoded['cities'] as $v){
echo 'ID: ' . $v['id'] . '<br>';
echo 'Name: ' . $v['name'];
echo '<br><br>';
}
Output:
ID: 3279
Name: Narasaraopet
ID: 1852
Name: Srirangapatna
To use it as objects, you can ommit the second argument, like so:
$decoded = json_decode($json);
Then you'd access the values object-like:
foreach($decoded->cities as $v){
echo 'ID: ' . $v->id . '<br>';
// ...
Read more about json_decode.
Use the function json_decode(), then you'll have an array.

PHP Best Way to Create Variable from API Content

I am very beginner in programmer and I am learning.
I am sorry if my question is too bad.
I want to create variable in php from api content, for example:
This contents is from this URL: http://example.com/api
{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}
<?php
$content = file_get_contents("http://example.com/api");
$content = str_replace('"', "", $content);
$content = str_replace(":", "=", $content);
$content = str_replace(",", "&", $content);
parse_str($content);
echo $name; //John
echo $age; //20
echo $genre; //male
echo $language //[{id <======== here is my problem
?>
My problem is when I am getting an array like "language", how to fix it?
Thanks for help.
U can use the http://www.php.net/json_decode in two ways :
This is object oriented :
$str = '{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}';
$json = json_decode($str);
echo 'name: ' . $json->{'name'} .'<br>';
echo 'age: ' . $json->{'age'} .'<br>';
echo 'genre: ' . $json->{'genre'} . '<br>';
foreach($json->{'language'} as $data){
echo 'id: ' . $data->{'id'} . '<br>';
echo 'name: ' . $data->{'name'} . '<br>';
}
As an associative array :
$json = json_decode($str, true);
echo 'name: ' . $json['name'] .'<br>';
echo 'age: ' . $json['age'] .'<br>';
echo 'genre: ' . $json['genre'] . '<br>';
foreach($json['language'] as $data){
echo 'id: ' . $data['id'] . '<br>';
echo 'name: ' . $data['name'] . '<br>';
}
json_decode() will help you to convert the string data to something more accessible:
<?php
// Instead of your fetched data we use static example data in this script
//$content = file_get_contents("http://example.com/api");
$content = '{"name":"John","age":"20","genre":"male","language":[{"id":"22","name":"english"},{"id":"23","name":"french"}]}';
// Convert json data to object
$data = json_decode($content);
// access object properties by using "->" operator
echo $data->name;
echo $data->age;
echo $data->genre;
// language is an array of objects, so let's look at each language object...
foreach($data->language as $lang) {
// ... and extract data using "->" again
echo $lang->id;
echo $lang->name;
}
A live example of this code can be found at http://sandbox.onlinephpfunctions.com/code/6df679c3faa8fff43308a34fb80b2eeb0ccfe47c
As pointed out by #fusionK, the response from the api request is a json string so convert to an object ( or array if preferred ) using json_decode ( json_decode( $data,true ) for an array )
Once it is decoded it is straightforward to access the properties of the object.
<?php
/* capture and decode response from api - creates an object */
$content = json_decode( file_get_contents("http://example.com/api") );
/* using object notation to access properties */
echo $content->name.' '.$content->age.' '.$content->genre;
/* for the language which is an array of objects */
$lang=$content->language;
foreach( $lang as $language ){
$obj=(object)$language;
echo $obj->id.' '.$obj->name;
}
?>

My Json isn't parsing properly

simple script gets a json file, strips out extraneous headers, and tried to access a single key/value with no luck. anyone?
CODE
$postURL = "http://case42.com/ogle/GetTarget.php?targetid=32feaf056b8c46e4a6f5500b6289cf59";
$json = file_get_contents($postURL);
echo "original response = <P>" . $json ."<HR>";
$strip = "target_record";
$mypos = strpos($json, $strip);
$json = substr($json,$mypos+15);
echo "My Trimmed json is: <P>" . $json."<HR>";
$obj = json_decode($json, true);
echo "<P>The print _ r of the trimmed json prints:<P> " . print_r ($json);
echo "<HR>";
echo "using \"\$obj->{'target_id'}\" to get name give me this: ".$obj->{'name'}."<HR>";
The results are:
original response =
GET
d41d8cd98f00b204e9800998ecf8427e
Mon, 16 Dec 2013 10:36:23 GMT
/targets/32feaf056b8c46e4a6f5500b6289cf59{"target_record":{"target_id":"32feaf056b8c46e4a6f5500b6289cf59","name":"Francesca Grace","width":300.0,"active_flag":true,"tracking_rating":5,"reco_rating":""},"status":"success","result_code":"Success","transaction_id":"23029749e4984e2d92dbfb5ff44f8834"}
My Trimmed json is:
{"target_record":{"target_id":"32feaf056b8c46e4a6f5500b6289cf59","name":"Francesca Grace","width":300.0,"active_flag":true,"tracking_rating":5,"reco_rating":""},"status":"success","result_code":"Success","transaction_id":"b427cb1f89544b4c85332ca0ad174848"}
The print_r of the trimmed json prints:
1
using "$obj->{'target_id'}" to get name give me this:
try this:
$postURL = "http://case42.com/ogle/GetTarget.php?targetid=32feaf056b8c46e4a6f5500b6289cf59";
$json = file_get_contents($postURL);
echo "original response = <P>" . $json ."<HR>";
$strip = "target_record";
$mypos = strpos($json, $strip);
$json = substr($json,$mypos-2);
echo "My Trimmed json is: <P>" . $json."<HR>";
$obj = json_decode($json, true);
echo "<P>The print _ r of the trimmed json prints:<P> " . print_r ($json);
echo "<HR>";
echo "using \"\$obj->{'target_id'}\" to get name give me this: ".$obj['tagret_record']['name']."<HR>";
Simple solution: using "true" in the json_decode converts the object to an associative array. Items inside are then accessed at $Array[$key][key].

Categories