Add new lines to JSON - php

I have successfully get content from the database and output the results in JSON. But I want to add a text that doesn't exists in the database and it's here I'm stuck.
$statement = $sql->prepare("SELECT data_filename,
data_filetype,
data_uniqid,
data_description,
data_coordinates,
exif_taken,
exif_camera,
exif_camera_seo,
exif_resolution,
exif_sensitivity,
exif_exposure,
exif_aperture,
exif_focallength,
is_downloadable,
is_notaccurate,
allow_fullsize
FROM photos
WHERE data_filename = 'P1170976'");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
That code gives me
[{"data_filename":"P1170976","data_filetype":"JPG","data_uniqid":"","data_description":"","data_coordinates":"","exif_taken":"0000-00-00","exif_camera":"","exif_camera_seo":"","exif_resolution":"","exif_sensitivity":"0","exif_exposure":"","exif_aperture":"","exif_focallength":"","is_downloadable":null,"is_notaccurate":null,"allow_fullsize":null}]
Which is correct of course but if I add these 2 new lines under $json = json_encode... I'm getting null.
$newdata = array('test' => 'just testing');
$json[] = $newdata;
What have I done wrong here?

json_encode() returns a string, so you can’t handle it as an array, i.e. add elements to string.
As noted in comments, you need to add those lines before json_encode() or decode it back to array using json_decode(), then apply the lines and then back json_encode().
Example about usage of json_encode and json_decode:
$array = array("this" => array("will" => array("be" => "json")));
$string = json_encode($array); // string(31) "{"this":{"will":{"be":"json"}}}"
// ...
$array2 = json_decode($string); // now it’s same array as in first $array
$array2["new"] = "element";
$string2 = json_encode($array2);
var_dump($string2); // string(46) "{"this":{"will":{"be":"json"}},"new":"string"}"

Try this:
$newdata = array('test' => 'justtesting');
$results[] = $newdata;
$json = json_encode($results);
or if you definately need it after its encoded:
$json = json_encode($results);
//lots of stuff
$jarray = json_decode($results, true);
$newdata = array('test' => 'justtesting');
$jarray[] = $newdata;
$json = json_encode($jarray);

Related

Concatenate JSON in php with read Database

I read user from the database but I return json to ajax only return the last user because I cant concatenate the json encode.
$myObj = new \stdClass();
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
$myJSON = json_encode($myObj);
}
echo $myJSON;
You are now overwriting $myJson in each iteration. We can also not "concatanate" two jsons (well, we could, but we shouldn't, cause it's laborious..).
Better put everything in one array/object and json_encode() at the very end.
$myObj = new \stdClass();
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
$myObj->NOMBRE = $fila["NOMBRE"];
$myObj->ROLENAME = $fila["ROLENAME"];
$myObj->IDUSER = $fila["IDUSER"];
// add objects to that array
$users[] = $myObj;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
Now here are some variants:
If you want everything that your db is returning in this items you could shorten that to:
$users = array(); // instantiate a new array
while ($fila = $bd->fila()) {
// add the whole item (cast as Object) to that array
$users[] = (Object) $fila;
}
// then at the end encode the whole thing to json:
echo json_encode($users);
If you don't care if the items are objects or arrays you could skip the casting and just add the array to the big array:
$users[] = $fila;
Maybe if you concatenate it as array like this
$myJSON[] = $myObj;
and then after the while
echo json_encode($myJSON);
You just have to collect data to big array and then encode whole array. Also there's no reason for creating new StdObjects instead of usual arrays.
// define empty array
$result = [];
while ($fila = $bd->fila()) {
// add to the array all needed elements one by one
$result[] = [
'NOMBRE' => $fila["NOMBRE"],
'ROLENAME' => $fila["ROLENAME"],
'IDUSER' => $fila["IDUSER"],
];
}
// encode whole result
echo json_encode($result);

how can produce json array with while in php

i want return my data from mysql to json array with do while loop.
when i return one record with json it is well. but i want return list of array in one json array.
how can do that with index in while? my code have error and i don't know how can do it. with one record it is well but more can't.
$json="array(";
do{
$json=."'$row_query['id']'=>array('fname'=>$row_query['fname'],'lname'=>$row_query['lname']),";
} while ($row_query = mysqli_fetch_assoc($query));
json=.")";
echo json_encode($json,JSON_UNESCAPED_UNICODE);
There's no need to add quotes, brackets, parentheses or whatever. json_encode function will do it for you. Just provide an array to it:
$json = [];
while ($row_query = mysqli_fetch_assoc($query)) {
$json[$row_query['id']] = [
'fname'=>$row_query['fname'],
'lname'=>$row_query['lname'],
];
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
This is the most super easy version. You may try this.
$json = new array();
do{
array_push($json,$row_query);
} while ($row_query = mysqli_fetch_assoc($query));
or
$json = [];
do{
$json[] = $row_query;
} while ($row_query = mysqli_fetch_assoc($query));
Atlast encode your json variable.
$json = json_encode($json);
echo $json;

get data from JSON with php

I am trying to get data from a JSON page:
http://www.oref.org.il/WarningMessages/alerts.json
I am getting errors.
How do I get the "data" array from the JSON?
Here is an example of what I am doing:
$homepage = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = json_decode($result);
$result = utf8_encode($result);
print_r($result);
json_encode returns an object (or an associative array if you give the second argument true). To get the data array, you need to use a property accessor:
$homepage = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = json_decode($homepage);
$data = $result->data;
print_r($data);
If you need to encode the $data array in UTF8, use:
$data = array_map('utf8_encode', $result->data);
To get the title, use:
$title = utf8_encode($data->title);
You could do this:
$result = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = json_decode($result);
print_r($result->data);
$result = file_get_contents ("http://www.oref.org.il/WarningMessages/alerts.json");
$result = iconv('UTF-16', 'UTF-8', $result);
$json = json_decode($result);
echo $json->id;
echo $json->title;
First of all, you are first json_decode($result); but $result has not been declared before this line.
Secondly, the logically order of your code is totally wrong:
$result = file_get_contents('http://www.oref.org.il/WarningMessages/alerts.json');
$result = utf8_encode($result); // encode the data before decoding json
$result = json_decode($result, true); // specify true to get an associated array
print_r($result);
Test.json:
{
"John":{
"name":"Json"
},
"James":{
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0
}
}
json.php:
$result= file_get_contents("test.json");
$get_data = json_decode($result, true);
echo $get_data['John']['name'].'<br/>';
echo $get_data['James']['age'];

Structure PHP array to pass to JS correctly

This works when we do this:
$db = $connection->messages;
$collection = $db->messagesCollection;
$messageArray = $collection->find(array('IDto' => '4'));
foreach($messageArray as $messageData){
$messageFrom = $messageData['IDfrom'];
$messageTo = $messageData['IDto'];
$messageTitle = $messageData['messageTitle'];
$messageIfRead = $messageData['ifRead'];
}
$JSONData = array('true', $messageFrom, $messageTo, $messageTitle, $messageIfRead);
echo $_GET['callback']."(".json_encode($JSONData).")";
But when we do this:
$db = $connection->messages;
$collection = $db->messagesCollection;
$messageArray = $collection->find(array('IDto' => '4'));
$JSONData = array('true', $messageArray);
echo $_GET['callback']."(".json_encode($JSONData).")";
and in the Javascript do this:
$.getJSON("mySite.com/pullData/getMail.php?callback=?",{
request: requestVar},
function(recievedData) {
alert(recievedData);
})
We get an alert of true, [object Object]
When using console log we get Object {}
How do we send that table data correctly?
I believe your biggest problem is the MongoCursor:
$messageArray = $collection->find(array('IDto' => '4'));
$JSONData = array('true', $messageArray);
echo $_GET['callback']."(".json_encode($JSONData).")";
You are trying to encode an object of MongoCursor there, hence the string representation is [object Object].
Try:
$messageArray = $collection->find(array('IDto' => '4'));
$JSONData = array('true', iterator_to_array($messageArray));
echo $_GET['callback']."(".json_encode($JSONData).")";
Instead. All find functions in MongoDB return a MongoCursor, the reason why your first code works is because you iterate the cursor building up your objects:
foreach($messageArray as $messageData){
$messageFrom = $messageData['IDfrom'];
$messageTo = $messageData['IDto'];
$messageTitle = $messageData['messageTitle'];
$messageIfRead = $messageData['ifRead'];
}
Note as well that the default json_encode of a document will contain objects, such as MongoId and MongoDate that do not encode too well into reusable JSON syntax. As such you will need to handle these types yourself.
Edit
Maybe a better way is to actually redo the indexes manually:
$messageArray = $collection->find(array('IDto' => '4'));
$d = array();
foreach($messageArray as $row){
$d = $row;
}
$JSONData = array('true', $d);
echo $_GET['callback']."(".json_encode($JSONData).")";
This way you will have a 0 based incrementing index instead of the ObjectId as each index base.

PHP read and write JSON from file

I have the following JSON in a file list.txt:
{
"bgates":{"first":"Bill","last":"Gates"},
"sjobs":{"first":"Steve","last":"Jobs"}
}
How do I add "bross":{"first":"Bob","last":"Ross"} to my file using PHP?
Here's what I have so far:
<?php
$user = "bross";
$first = "Bob";
$last = "Ross";
$file = "list.txt";
$json = json_decode(file_get_contents($file));
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
?>
Which gives me a Fatal error: Cannot use object of type stdClass as array on this line:
$json[$user] = array("first" => $first, "last" => $last);
I'm using PHP5.2. Any thoughts? Thanks!
The clue is in the error message - if you look at the documentation for json_decode note that it can take a second param, which controls whether it returns an array or an object - it defaults to object.
So change your call to
$json = json_decode(file_get_contents($file), true);
And it'll return an associative array and your code should work fine.
The sample for reading and writing JSON in PHP:
$json = json_decode(file_get_contents($file),TRUE);
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
Or just use $json as an object:
$json->$user = array("first" => $first, "last" => $last);
This is how it is returned without the second parameter (as an instance of stdClass).
You need to make the decode function return an array by passing in the true parameter.
json_decode(file_get_contents($file),true);
Try using second parameter for json_decode function:
$json = json_decode(file_get_contents($file), true);
This should work for you to get the contents of list.txt file
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str=utf8_encode($str);
$str=json_decode($str,true);
print_r($str);
If you want to display the JSON data in well defined formate you can modify the code as:
file_put_contents($file, json_encode($json,TRUE));
$headers = array('http'=>array('method'=>'GET','header'=>'Content: type=application/json \r\n'.'$agent \r\n'.'$hash'));
$context=stream_context_create($headers);
$str = file_get_contents("list.txt",FILE_USE_INCLUDE_PATH,$context);
$str1=utf8_encode($str);
$str1=json_decode($str1,true);
foreach($str1 as $key=>$value)
{
echo "key is: $key.\n";
echo "values are: \t";
foreach ($value as $k) {
echo " $k. \t";
# code...
}
echo "<br></br>";
echo "\n";
}
When you want to create json format it had to be in this format for it to read:
[
{
"":"",
"":[
{
"":"",
"":""
}
]
}
]

Categories