php json_decode for the contents of a .txt file - php

When I do the following,
$res1 = '{"n":2,"stuff":[{"key1":"value1","key2":"value2"}]}';
$res1 = json_decode($res);
var_dump($res1);
It outputs:
object(stdClass)#289 (2) { ["n"]=> int(2) ["stuff"]=> array(1) { [0]=> object(stdClass)#288 (2) { ["key1"]=> string(6) "value1" ["key2"]=> string(6) "value2" } } }
However, when I save the string $res1 into a .txt file named string.txt with the contents:
'{"n":2,"stuff":[{"key1":"value1","key2":"value2"}]}'
I do:
$filename = "path/string.txt";
$res2 = file_get_contents($filename);
$res2 = json_decode($res2);
It outputs:
NULL
How can I use json_decode for $res1 from a .txt file the same way as I can use json_decode for $res1 after declaration?
To Whom It May Concern:
A reason not mentioned about why it wasn't working for me was because my code editor didn't like the apostrophes (as in Name's) when declaring a $res1 with apostrophes, and I escaped the apostrophes as \' that became present in the string.txt file used for $res2.

Related

Store json data to php variable

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

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.

How can two arrays created in the same way become different?

The var_dumps of the two arrays are different but they were created the exact same way . Why is this?????
first array dump:
array(2) {
[0]=>
array(0) {
}
[1]=>
string(6) ",2,2,1"
}
second array dump:
array(3) {
[0]=>
array(0) {
}
[1]=>
string(1) "2"
[2]=>
string(1) "2"
[3]=>
string(1) "1"
}
array 1 is made on fileA.php
while ($row = mysql_fetch_assoc($res))
{
$iState[] = $row["state"];
}///end while
then i use ajax to send to fileB.php
js_array=<? echo json_encode($iState); ?>;
var url_js_array=js_array.join(',');
xmlhttp.open("GET","fileB.php?istate="+ url_js_array,true);
xmlhttp.send();
then in fileB.php(ajax response file) i retrieve the array
$iStateValues[] =$_GET["istate"] ;
then I create array 2 on fileB.php
while ($row = mysql_fetch_array($res))
{
$currentiState[]= $row["state"];
}///end while
then I compred the two
echo"\n\nsame test\n";
if($iStateValues==$currentiState)
echo "same";
else
echo "not same";
The problem:
Currently, you're sending the comma-separated string to fileB.php.
$iStateValues[] = $_GET["istate"] ;
$_GET["istate"] contains the comma-separated string, and in the above statement, you're pushing the value into an empty array $iStateValues.
Now, in fileB.php, you create another array $currentiState using a while loop. Then you try to compare them.
$iStateValues is a string, not an array. $currentiState is a real array. So the comparison will always return FALSE.
How to fix the issue:
Instead of sending the comma-separated string to fileB.php, send the actual JSON string. So your code will look like:
js_str=<? echo json_encode($iState); ?>;
xmlhttp.open("GET","fileB.php?istate="+ js_str,true);
xmlhttp.send();
Now, in fileB.php, you can receive the JSON string and then decode it, like so:
$jsonArray = json_decode($_GET['istate'], true);
(The second parameter in JSON decode says it should be decoded to an associative array instead of an object).
Then do the comparison.

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

Newbie PHP: Insert a variable for echoing

I'd like to be able to echo $domain from this
$domain = $response['results']['$MYVAR']['shortUrl'];
I've tried curly braces and various other ways of formatting $MYVAR but the syntax is wrong.
Help most welcome !
EDIT --> var_dump($response):
object(stdClass)#1 (4) {
["errorCode"]=> int(0)
["errorMessage"]=> string(0) ""
["results"]=> object(stdClass)#2 (1) {
["http://www.domain.com"]=> object(stdClass)#3 (5) {
["userHash"]=> string(6) "oSEMki"
["shortKeywordUrl"]=> string(0) ""
["hash"]=> string(6) "oms2ZB"
["shortCNAMEUrl"]=> string(20) "http://bit.ly/LALALA"
["shortUrl"]=> string(20) "http://bit.ly/LALALA"
}
}
["statusCode"]=> string(2) "OK"
}
I can see the "domain.com" element fine but when I do this:
var_dump($response['results'][$MYVAR]);
it returns NULL ! Which must be why $domain = $response['results'][$MYVAR]['shortUrl']; fails too. Odd !
--EDIT 2 --
var_dump($MYVAR); gives:
string(118) "http://www.domain.com"
Try this:
$domain = $response['results'][$MYVAR]['shortUrl'];
echo $domain;
Are you sure it's stored in a 3 dimentional array like that?
Because that looks like needless complication.
Try it without quotes
$domain = $response['results'][$MYVAR]['shortUrl'];
or use double quotes
$domain = $response['results']["$MYVAR"]['shortUrl'];
EDIT:
In reaction to your edit. You are accessing variable like an associative array but the variable is instance of stdObject. So if you want to acces it, you must retype it like this:
$tmp = (array) $response;
$domain = $tmp['results'][$MYVAR]['shortUrl'];
or access it like object
$domain = $tmp->results->$MYWAR->shortUrl;
EDIT 2:
So it is strange, because http://www.domain.com is not 118 characters long, as var_dump wrote.
Where and how did you filled up the variable $MYVAR?
$domain = $response['results'][$MYVAR]['shortUrl'];
You don't need quotes around $MYVAR.
Have you tried without the quotes around $MYVAR?
It's an object.
$domain = $response->results->$MYVAR->shortUrl;

Categories