Store json data to php variable - php

im trying to store data from a json file to php variables. But it wont work when i try to echo the variable for later use.
This is my json file:
"[{\"channelId\":150342342,\"channelName\":\"example.no\",\"channelUrl\":\"http:\/\/www.example.no\"},{\"channelId\":1529564329,\"channelName\":\"example2.no\",\"channelUrl\":\"http:\/\/www.example2.no\"},{\"channelId\":1536534822,\"channelName\":\"example3.no\",\"channelUrl\":\"http:\/\/www.example3.no\"}]"
This is my code:
<?php
require_once('config.php');
$channeljson = file_get_contents('channels.json');
$data = json_decode($channeljson, true);
$channelid = $data['channelId'];
$channelname = $data['channelName'];
$channelurl = $data['channelUrl'];
I have tried many other ways too..
Anyone have any tips that could work?

Your file contains a json that represents a string, since it starts and finishes with the " character. Another issue are the escape characters \.
If you don't want to change de routine that writes the json files, you can solve your problem by correcting the invalid json:
$data = json_decode(trim(stripslashes($channeljson), '"'), true); // Removes the escape and the enclosing " characters
There is one more problem: the json represents an array of objects (arrays since you are passing true to the second json_decode function) and you are trying to access $data like a regular array.
See the $data contents:
array(3) {
[0]=>
array(3) {
["channelId"]=>
int(150342342)
["channelName"]=>
string(10) "example.no"
["channelUrl"]=>
string(21) "http://www.example.no"
}
[1]=>
array(3) {
["channelId"]=>
int(1529564329)
["channelName"]=>
string(11) "example2.no"
["channelUrl"]=>
string(22) "http://www.example2.no"
}
[2]=>
array(3) {
["channelId"]=>
int(1536534822)
["channelName"]=>
string(11) "example3.no"
["channelUrl"]=>
string(22) "http://www.example3.no"
}
}

Related

PHP: how can I access JSON object

I'm sending this JSON:
[{"tipo":""},{"activo":""},{"titulo":"Servicoasd B"},{"texto":"asdasdasd"}]
to a php file via post method.
There, i do
$obj = json_decode($_POST['sentJson']);
However, I seem to be unable to access the elements of the JSON.
var_dump(($obj));
Shows the object:
array(4) {
[0]=>
object(stdClass)#2 (1) {
["tipo"]=>
string(0) ""
}
[1]=>
object(stdClass)#3 (1) {
["activo"]=>
string(0) ""
}
[2]=>
object(stdClass)#4 (1) {
["titulo"]=>
string(9) "Servico B"
}
[3]=>
object(stdClass)#5 (1) {
["texto"]=>
string(6) "asdasd"
}
}
But if I try
$obj['texto'];
$obj->{'texto'};
$obj[0]['texto'];
$obj[0];
It shows "undefined index texto" or "trying to get property of non object in" and the last one "Object of class stdClass could not be converted to string in". I'm very new to PHP, but still I can't seem to notice what I'm doing wrong. Any help would be appreciated.
Your JSON is a serialized array of four completely different objects, so when you run json_decode, that's what you get: an array.
If you want to access your objects inside that array, access them like you would any other indexed array:
$list = json_decode(...);
foreach($list as $obj) {
var_dump($obj)
}
Or target them explicitly using plain old numerical access.
$list = json_decode(...);
$last = $list[3];
$text = $last->texto;
But really the question you should be asking is why this is the JSON you get. An array with completely different objects at each position is terrible data, and should be fixed.

in php, How can I extract a JSON from an array?

I'm receiving a string from the database and I only want to use the JSON so I can use a json_decode on it.
this is the string:
array(1) { [0]=> array(4) { ["reporte_id"]=> int(1) ["tabla_id"]=> int(1) ["configuracion"]=> string(1000) "{"tabla":"servtp","config":[{"name":"Client","type":"smallint","notnull":"0","pk":"0"},{"name":"Distribuidor_","type":"varchar(40)","notnull":"0","pk":"0"},{"name":"Branch","type":"smallint","notnull":"0","pk":"0"},{"name":"Cve","type":"smallint","notnull":"0","pk":"0"},{"name":"FechaApertura","type":"date","notnull":"0","pk":"0"},{"name":"FechaFactura","type":"date","notnull":"0","pk":"0"},{"name":"Dias","type":"smallint","notnull":"0","pk":"0"},{"name":"WorkingDays","type":"real","notnull":"0","pk":"0"},{"name":"Mes_","type":"smallint","notnull":"0","pk":"0"},{"name":"NumeroOT","type":"varchar(10)","notnull":"0","pk":"0"},{"name":"VentasNetas_","type":"real","notnull":"0","pk":"0"},{"name":"TipoOrden","type":"varchar(30)","notnull":"0","pk":"0"},{"name":"Type","type":"varchar(3)","notnull":"0","pk":"0"},{"name":"Taller","type":"varchar(30)","notnull":"0","pk":"0"},{"name":"Clasificacion_","type":"varchar(16)","notnull":"0","pk":"0"},{"name":"Retencion_","type":"varchar(1)","notnull":" ["nom_reporte"]=> string(33) "Monthly Service Operation Report " } }
If the variable is called $variable, ... you have to:
$json = $archivio[0]['configuration'];
$arrayConf = json_decode($json);
The string you are presenting is a var_dump of a php array, it is not properly formed. Where you are getting that string from should fix their side to properly format the array formatting.

PHP stdClass object - adding element not working

I have a problem, I fetched all the rows from DB using PDO::FETCH_OBJ.
The response is completely okay. But I would like to loop through it and add an element with name 'photo' to each object in the array. This photo will include a small image converted to string.
foreach ($rows as $row) {
$row->photo = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/xxx/uploads/'.$row->id.'/'.$row->filepath.'_thumbnail.jpg');
}
Pictures are being found without any problems, and even after I echo their content after I add it to $row, I get their contents without any problem too. But when I return the $rows variable, and I try to receive it in Android, the photo element is never there. What could be the problem?
This is how i return:
return base64_encode(json_encode($rows));
Example of output:
object(stdClass)#3 (10) {
["position"]=> string(1) "1"
["id"]=> string(2) "24"
["fbname"]=> string(12) "Vl Mar"
["filepath"]=> string(13) "1481809734438"
["photo"]=> string(5760) "������JFIF���� .....and many more characters
}
Formatting at the end of output is not important, as its not Base64 decoded.

handling json data with php

My json data is:
{"jsondata":[[1,7,16,29,41,45],[2,12,21,31,36,45]]}
There are 2 sets of numbers and each set has 6 different number. And the number of total sets can be more according to user's input. So, there may be 3 sets which means 18 numbers, etc. If I copy/paste that in to http://json.parser.online.fr/ , I see no error. So, json data is correct, I guess.
Second, here is my PHP file:
<?php
$input = file_get_contents('php://input');
$result=json_decode($input);
var_dump($result);
?>
That works fine too. I mean, when I run these lines, in the chrome's developer tool, I can see these:
object(stdClass)#1 (1) {
["jsondata"]=>
array(2) {
[0]=>
array(6) {
[0]=>
int(1)
[1]=>
int(7)
[2]=>
int(16)
[3]=>
int(29)
[4]=>
int(41)
[5]=>
int(45)
}
[1]=>
array(6) {
[0]=>
int(2)
[1]=>
int(12)
[2]=>
int(21)
[3]=>
int(31)
[4]=>
int(36)
[5]=>
int(45)
}
}
}
So far, I think, what I have to understand is json data is correct and php can respond it back. So, how can I reach this numbers and assing them into another variable in PHP? My actual aim is send them into the mysql. If I can get them, it is easy.
Some says use key/value pair thing but the problem is, my json data creates itself according to user's input. User clicks some numbers and then the number get appended into the json data. And it continues each of six clicks:
function createjson(){
var c=1;
var json='{"jsondata":[[';
$("#kup td").each(function(){
if($(this).html()!="" && $(this).html()!="SELECTED NUMBERS")
{
json+= parseInt($(this).html())+',';
if($(this).index()%5==0 && $(this).index()!=0) //sixth number selected
{
json=json.substring(0,json.length-1);
json+="],["
}
}
});
json=json.substring(0,json.length-3);
json+="]]}";
return json;
};
I thought I found my answer here but it didn't work either or I did somethings wrong. I am very newbie on these json stuffs, so please don't force me to change whole thing. There must be a way to reach this values. So, please save me guys :-)
You can use json_encode function with second parameter to convert JSON string into array:
$input = '{"jsondata":[[1,7,16,29,41,45],[2,12,21,31,36,45]]}';
$data = json_decode($input, TRUE);
var_dump($data['jsondata']);
In this case you should get associated array that simply for using

PHP JSON read object attribute

I am a beginner in php rogramming and I try to get some information per PHP out of an JSON string.
Therefore I used:
$json = file_get_contents('data.json')
var_dump(json_decode($json));
to get more information how php will parse my JSON file. Output of it looks like:
array(10) {
[0]=> object(stdClass)#1 (1) {
["links"]=> array(4) {
[0]=> object(stdClass)#2 (6) {
["localIP"]=> string(14) "172.29.126.189"
["remoteIP"]=> string(14) "172.29.118.193"
["validityTime"]=> int(586277)
["linkQuality"]=> float(1)
["neighborLinkQuality"]=> float(0.396)
["linkCost"]=> float(2.524) }
[1]=> object(stdClass)#3 (6) {
["localIP"]=> string(14) "172.29.126.189"
["remoteIP"]=> string(14) "172.29.149.193"
["validityTime"]=> int(551339)
["linkQuality"]=> float(1)
["neighborLinkQuality"]=> float(0.396)
["linkCost"]=> float(2.524) } } } }
...
I want to know how I would be able to display for example:
the "remoteIP" Attribute of Links[0]
all Attributes of Links[0]
Thank you for your suggestions
Whenever you have an array, you use square brackets to access any index of it. Whenever you have an object, you use the -> operator to access a property of it.
So for your examples, it would be:
$json = file_get_contents('data.json');
$data = json_decode($json);
var_dump($data[0]->links[0]->remoteIP); // remoteIP of links[0]
var_dump($data[0]->links[0]); // All attributes of links[0], as object
Another way would be (as Leo Bali pointed out), to let PHP convert all objects to arrays. In that case, you always use square brackets:
$json = file_get_contents('data.json');
$data = json_decode($json, true); // Add true here as second parameter
var_dump($data[0]['links'][0]['remoteIP']); // remoteIP of links[0]
var_dump($data[0]['links'][0]); // All attributes of links[0], as array

Categories