appending content to json file using php script - php

I am trying to append content to json file using php script.
output of file1 is
[
{"id":"filters","name":"filter_supptype_cp_01"}
]
output of file2 is
[
{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
after appending the output should come as :
[
{"id":"filters","name":"filter_supptype_cp_01"},
{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
but output is coming as : -
[
{"id":"filters","name":"filter_supptype_cp_01"}]
[{"id":"drives","name":"hddcntrlr"},
{"id":"drives","name":"diskdrivedes"}
]
Code that I have tried is:
$file = file_get_contents('makejson.json');
$data = json_decode($file);
$info[] = array('id'=>$attribute1, 'name'=>$sub_attr_name);
$newb = array_values((array)$info);
file_put_contents('makejson.json',json_encode($newb),FILE_APPEND);
please help!!!!

Decode both files, append the array, encode again:
$existingData = json_decode(file_get_contents('file1.json'));
$newData = json_decode(file_get_contents('file2.json'));
$existingData = array_merge($existingData, $newData);
file_put_contents('file1.json', json_encode($existingData));

The array_push() function inserts one or more elements to the end of an array.
Your code :
$file = file_get_contents('makejson.json');
$tempArray = json_decode($file);
array_push($tempArray, $data); // $data is your new data
$jsonData = json_encode($tempArray);
file_put_contents('makejson.json', $jsonData);

i hope this code to help to yoo after 6 ear.
if (isset($_POST['data']) && $_POST['data']) {
$dbfile = file_get_contents('data.json');
$data = json_decode($dbfile);
unset($dbfile);
$yourdata = $_POST['data'];
$data[] = $yourdata;
file_put_contents('data.json', json_encode($data));
unset($data); }

You don't need to append array. You need to overwrite it.
Try like:
$file = file_get_contents('makejson.json');
$data = json_decode($file);
$data[] = array('id'=>$attribute1, 'name'=>$sub_attr_name);
file_put_contents('makejson.json',json_encode($data)); //Overwrite it
It will overwrite with new array.

Related

How to get the value from json with PHP

How can I get the source, title, issn, author, ... from a json file: JSON file
We tried with:
$new_pmid = $_POST['new_pmid'];
$api_json_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=pubmed&id=".$new_pmid."&retmode=json";
$json = file_get_contents($api_json_url);
$data = json_decode($json, TRUE);
echo $header[0]->result->$new_pmid->title;
....
But nothing happen...
Can you give me the solution for the json file (generated from pubmed database).
Thank you.
You didn't use the $data variable, which stored the decoded data
You decode JSON into $data as array
$title = $data['result'][$new_pmid]['title'];
$issn = $data['result'][$new_pmid]['issn'];
$authors = $data['result'][$new_pmid]['authors'];
--Update--
To get $authors name ,authtype ,... use foreach loop:
foreach($authors as $author){
$name = $author['name'];
$authtype = $author['authtype'];
$clusterid = $author['clusterid'];
}

Reformat JSON array using PHP

I have a small PHP script that pulls in a CSV file and creates a JSON array from this.
However, I'd like to change the formatting of my outputted JSON array.
PHP:
<?php
$file = fopen('food.csv', 'r');
$allfile = [];
$idsColumnsWanted = array_flip([0, 1, 2]);
while (false !== $fields = fgetcsv($file)) {
$allfile[] = array_intersect_key($fields, $idsColumnsWanted);
}
fclose($file);
?>
Output:
var data = [["McDonalds","Fast Food","London"],["Marios","Italian","Manchester"]];
How do I transform my CSV into the following:
var data = [
{name:"McDonald's Fast Food",location:"London"},
{name:"Marios Italian",location:"Manchester"}
];
So it basically merges the first 2 items and adds name & location.
My food.csv file is:
McDonalds,Fast Food,London
Marios,Italian,Manchester
Next time please try something by yourself:
$data = [["McDonalds", "Fast Food", "London"], ["Marios", "Italian", "Manchester"]];
$newData = [];
foreach ($data as $info) {
$newData[] = [
'name' => $info[0] . " " . $info[1],
'location' => $info[2]
];
}
var_dump(json_encode($newData));
Output
string '[{"name":"McDonalds Fast Food","location":"London"},{"name":"Marios Italian","location":"Manchester"}]' (length=104)
You need to create a new array in the desired format, and simple json_encode it.
If you consider using jQuery - there it is
var data = [["McDonalds","Fast Food","London"],["Marios","Italian","Manchester"]];
var formated_data = {};
$.each(data, function(key, val) {
formated_data[key] = {name: val[0] + ' ' + val[1], location: val[2]}
});
console.log(formated_data);
Open CSV File then parse the CSV into an array.
Flow this Line,
<?php
$file="1_23.csv";
$csv= file_get_contents($file);
$array = array_map("str_getcsv", explode("\n", $csv));
$json = json_encode($array);
print_r($json);
?>

How do I decode url data and access in array and decode % value from urls

I'm trying this code to get info from json and array but I can't decode %values from the data and can't access the array any one can help me?
$url = 'http://www.example.com/video?&video_id=MvK7ibgRREw&asv=3&el=detailpage&hl=en_US';
$data = file_get_contents($url);
header('Content-Type: application/json');
echo $data;
this should work...
$url = 'http://www.youtube.com/get_video_info?&video_id=MvK7ibgRREw&asv=3&el=detailpage&hl=en_US';
$data = file_get_contents($url);
$array = explode('&', $data);
for ($i=0; $i<count($array); $i++){
$array[$i] = urldecode($array[$i]);
}
$json = json_encode($array);
echo $json;

Add new lines to JSON

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

Too much JSON info

I am using the following to convert data from mysql to JSON:
$sql = "select img_name from user_gallery_images where user_id=$_SESSION[user_id]";
$response = array();
$posts = array();
$result = $mysqli->query($sql);
while($row = $result->fetch_array()){
$file=$row['img_name'];
$fileDir = "gallery/$file.jpg";
$posts[] = array('thumb'=> $fileDir, 'image'=> $fileDir);
}
$response['posts'] = $posts;
$fp = fopen('/home/public_html/users/'.$settings[username].'/gallery/gallery.json', 'w');
$jsonData = stripslashes(json_encode($response));
fwrite($fp, $jsonData);
fclose($fp);
Which works well and creates e.g.
{"posts":
[
{"thumb":"gallery/tess1367386438.jpg","image":"gallery/tess1367386438.jpg"},
{"thumb":"gallery/tess1367386538.jpg","image":"gallery/tess1367386538.jpg"}
]
}
But, the JQuery plug in i'm using it with won't read it with the outer "posts" container
QUESTION:
How can I strip the outer "posts" container in the JSON to produce only:
[
{"thumb":"gallery/tess1367386438.jpg","image":"gallery/tess1367386438.jpg"},
{"thumb":"gallery/tess1367386538.jpg","image":"gallery/tess1367386538.jpg"}
]
Try
$jsonData = json_encode($response['posts']);

Categories