I'm using wordpress with nextgen gallery, and i would like to get the images from a specific gallery id in a seperate JSON file. So far i have this code, but that just exports the images from the given ID (in this case; 7). I know there must be some kind of foreach function, but my javascript knowledge won't go that far.
Could someone help me with this one? The code i have so far:
mysql_connect("localhost","DB-NAME","DB-PASSWORD");
mysql_select_db("DB-NAME");
$result=mysql_query("SELECT filename FROM zs_ngg_pictures WHERE galleryid = '7' ORDER BY sortorder LIMIT 3");
while($row=mysql_fetch_assoc($result)){
$output[]=$row;
}
$fp = fopen('result.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
echo json_encode($output);
If I correctly understand what you're trying to achieve you can simply get all the pictures, put them in a multidimensional array:
$result=mysql_query("SELECT filename, galleryid FROM zs_ngg_pictures ORDER BY sortorder");
while($row=mysql_fetch_assoc($result)){
$output[$row['galleryid']][] = $row['filename'];
}
and you have a PHP array like this (if you got two galleries with id 7 and 23):
array(
7 => array('file7-1.jpg','file7-2.jpg','file7-3.jpg'),
23 => array('file23-1.jpg','file23-2.jpg'),
);
so the result.json file will be like:
{ "7" : ["file7-1.jpg", "file7-2.jpg", "file7-3.jpg"],
"23" : ["file23-1.jpg", "file23-2.jpg"] }
If you want separate files for each galleryid you can then loop and save files with different names:
foreach($output as $gall_id => $gallery) {
file_put_contents('result-'.$gall_id.'.json', json_encode($gallery));
}
and you'll have two files named result-7.json and result-23.json
Instead of doing complicated fopen() stuff and echo:
$fp = fopen('result.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
echo json_encode($output);
you can simply call:
file_put_contents('result.json', json_encode($output));
readfile('result.json');
or you skip the file and simple output the JSON:
echo json_encode($output));
Related
I'm trying to display only the rows that contain a specific word in a specific column. Basically I would like to show only the rows that have "yes" in the Display column.
First_Name, Last_Name, Display
Kevin, Smith, yes
Jack, White, yes
Joe, Schmo, no
I've been trying various things with fgetcsv & str_getcsv from other answers and from php.net but nothing is working so far.
It doesn't do anything but this is my current code:
$csv = fopen('file.csv', 'r');
$array = fgetcsv($csv);
foreach ($array as $result) {
if ($array[2] == "yes") {
print ($result);
}
}
Let's have a look at the documentation for fgetcsv():
Gets line from file pointer and parse for CSV fields
fgetcsv reads a single line, not the whole file. You can keep reading lines until you reach the end of the file by putting it in a while loop, e.g.
<?php
$csv = fopen('file.csv', 'r');
// Keep looping as long as we get a new $row
while ($row = fgetcsv($csv)) {
if ($row[2] == "yes") {
// We can't just echo $row because it's an array
//
// Instead, let's join the fields with a comma
echo implode(',', $row);
echo "\n";
}
}
// Don't forget to close the file!
fclose($csv);
You should use data tables.
https://datatables.net/examples/basic_init/zero_configuration.html
That's how I deal with my textfiles. But be carefull, with a large amount of Data (> 10000 rows) you should have a loog at the deferRender option.
https://datatables.net/reference/option/deferRender <-- JSON DATA required.
I've got a CSV file with product information for a e-commerce platform. The CSV file contains multiple rows with same product ID and multiple description. Each value is seperated by "^" instead of comma.
What i want to achieve is to combine these multiple rows into one and comma seperated and have only 1 row with the product information. So my problem is to combine multiple rows with same attribute.
Here is the formating of the file today
productID^Element^Value<br>
id01^Status^01<br>
id01^edited^2016-01-01<br>
id01^Longdesc^Here goes the description<br>
id01^Longdesc^Here is the second line of description<br>
id01^longdesc^And the third row<br>
id01^image^Link to image 1<br>
This is what i'm looking for to achieve:
ID01, 2016-01-01, Here goes the description Here is the second line of description And the third row, link to image
The other idea is to put structure to an nice XML file.
Hope you guys have some good solutions for this and can help me out.
Thank you!
Please try to bellow code. I am sure this code will work fine.
public function import_product_from_csv() {
ini_set('max_execution_time', 1000);
$fh = fopen('your_csv_file.csv', 'r');
fgets($fh, 4096);
while (!feof($fh)) {
$buffer = fgets($fh, 4096);
$arrTemp = explode('^',$buffer);
if($arrTemp[0] != "") {
$data = array(
'productID' => $arrTemp[0], // codice provincia
'Element' => $arrTemp[1], //codice comune
'Value' => $arrTemp[2] //denominazione
);
$sql_query = "insert into table_name (productID, Element, Value) values ('".$arrTemp[0]."', '".$arrTemp[1]."', '".$arrTemp[2]."')";
mysql_query($sql_query);
}
/*echo "<pre>";
print_r($arrTemp);
echo "</pre>";*/
}
fclose($fh);
echo "Uploaded";
}
Happy code...
I am using file_put_contents to create and add info to a json file. This works successfully, however I need to create two files with different names (title.json and dates.json) - is this possible?
The reason I need to do this is because I am using twitter typeahead and it seems to only work with separate json files.
It works with a single file i.e;
file_put_contents(URL . '/title.json', json_encode($data));
However not with this;
file_put_contents(URL . '/title.json', '/dates.json',
json_encode($data));
I receive the following error message;
Warning: file_put_contents() expects parameter 3 to be long, string
given in C:\xampp\htdocs... on line 23
$sql = ("SELECT DISTINCT pub_id, title, place_name, party_name, publication_date FROM vw_ft_search");
$data = array();
while($row = $result->fetch_assoc())
{
$data[] = array('title' => utf8_encode($row['title']),
'pub_id' => utf8_encode($row['pub_id']),
'place_name' => utf8_encode($row['place_name']),
'party_name' => utf8_decode($row['party_name']),
'publication_date' => $row['publication_date']);
}
file_put_contents(URL . '/title.json','/dates.json', json_encode($data)); //line 23
I am probably missig something very easy, any advice is appreciated.
file_put_contents only accepts one file. Use a loop to insert in all files ->
$files = array('/title.json', '/dates.json');
then iterate through $files:
foreach($files as $file)
{
file_put_contents(URL.$file, json_encode($data));
}
Working on a website and need to store data for each user. Currently using json files and the way it is set up currently it overwrites the data each time.
1st question, is using one json file the best way to house this data or should I set up a directory for each user?
2nd question, if one file is the best way to go, how do I append 'unique' data? I found some example code from the posts on "Overwrite JSON if fields match PHP" but it is not working for me. It is not writing to the file at all now.
Original code:
$posts[] = array('vhclID'=> $vhclID, 'statVal1'=> $engStat, 'statVal2'=> $brakeStat);
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Revised code to be able to append new data and eliminate redundancies(Does not work):
$file = file_get_contents('results.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[vhclID] = array('vhclID'=> $vhclID, 'statVal1'=> $engStat,
'statVal2'=> $brakeStat);
//save the file
$data = array_values($data);
file_put_contents('results.json',json_encode($data));
echo json_encode($data);
unset($data);//release memory
Thanks for your help!!
You should use a database if you're storing typical user data; clearly you don't want to load megabytes of user data just to observer or modify one field for one user.
If you have some posted data, and I understand your question correctly, you might do something like this (but add more security):
$new_data = $_POST[];
foreach ($new_data as $name=>$datum) {
if (empty($data[vhclID][$name]) {
// This means that this field is unique
$data[vhclID][$name] = $datum;
}
}
And then just save that data to your JSON file.
$fp = fopen('results.json', 'r');
$postjson = json_decode(fread($fp, 1024*1024), true);
fclose($fp);
$posts = ($posts==array()) array('vhclID'=> $vhclID, 'statVal1'=> $engStat, 'statVal2'=> $brakeStat) : $postjson['posts'];
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Should do what you want.
Modify $posts.
I mess around with PHP and json data a lot.
One thing I've noticed is that json_decode will create a PHP object(stdClass) by default
Example
Contents of results.json >>> {"example":"test"}
$file = file_get_contents("results.json");
$json = json_decode($file);
var_dump($json); // Outputs: object(stdClass)#14 (1) { ["example"]=> string(4) "test" }
If you add true as the second parameter to json_decode you end up with an array instead
Example
$file = file_get_contents("results.json");
$json = json_decode($file, TRUE); // Added TRUE as second parameter
var_dump($json); // Outputs: array(1) { ["example"]=> string(4) "test" }
Once you have your appropriate data, you can modify and change the $json however you want and then re-write it to the .json file.
So for question 1: Having an individual json file for each user (eg: userID-001.json, userID-002.json) is probably the better way to go.
For question 2: You can take the individual file, grab the contents and store it in a PHP array using json_decode($data, TRUE) // with true as second parameter if you want an array and then modify the array and resave it (using json_encode).
Hope this helps~!
Im using PHP to create a playlist. Two random songs are chosen from a directory, and their name and location are stored in an array and then written to a file via json_encode().
$arraySongs[] = array('name' => $songName , 'mp3' => $webUrl);
This works great. I can make a very long playlist, two songs at a time. Id also like to remove songs, so I have an AJAX powered delete button, that posts the id of the track to be deleted, PHP then loads the whole tracklist...
$decoded = json_decode(file_get_contents($tracklist),true);
and removes the given song from the array, then re encodes and re writes the json text file. This all works great.
The problem comes whenever I try to delete anything with a playlist of more than 10 items.
Typically, my song.json file goes [{name:song1,mp3:song url},{name:song2,mp3:song2 url}]
However, when I have a list of more than 10 items, the re encoded playlist looks like this:
[{ ... },{name:song9,mp3:song9 url}],[10,{"name":song10,mp3:song10 url}]
Why is my re-encoded array get that strange [10,{"name"... [11,{"name"... [12,{"name"...
but everything below 10 is always fine?
Thanks for reading this! Any suggestions would be greatly appreciated, this is driving me nuts!
Here is the code im Using:
<?php
$json = "song.php";
$decoded = json_decode(file_get_contents($json),true);
$playlist = array();
$names = array();
// Now Get i From Javascript
$i=$_POST['id'];
//Select i's Array
$collect_array=$decoded[$i];
while (list ($key, $val) = each ($collect_array)) {
//Remove i's Values
//echo "<br />$key -> $val <br>";
unset($decoded[$i]);
}
//Take all the remaining arrays
$collect_array=$decoded;
while (list ($key, $val) = each ($collect_array)) {
$arraySongs[] = array($key , $val);
}
// Our New Array ready for json.
$jsonData = json_encode($arraySongs);
// open song.php and scribble it down
$tracklist = $json;
$fh = fopen($tracklist, 'w') or die("can't open filename: $tracklist");
fwrite($fh, $jsonData);
fclose($fh);
?>
try removing elements with unset
debug your code (not posted in the thread, so do it yourself) by adding a line where you var_dump or print_r the whole thing before json_encode
or it's a bug in json_encode which would not be nice...
Encode the track ID on 2 or even 3 digits using the php function sprintf with parameter %02d.
This worked fine for me.