I am making a quiz script. I want a "teacher" to be able to edit the questions. Originally, I tried to use mySQL but it was a bit difficult, so I decided to switch to a JSON file.
After doing some basic checks with PHP, I wrote this block of code
$json = array();
for ($x=1; $x < $count + 1; $x++) {
$q_and_a = array(
"Question" => $_POST["q".$x],
"Answer" => $_POST["a".$x]
);
array_push($json, $q_and_a);
}
$encoded_array = json_encode($json);
// Delete JSON file, create new one and push encoded array into file
$json_file = 'questions.json';
unlink($json_file);
$handle = fopen($json_file, 'w') or die('Cannot open file: '.$json_file);
fwrite($handle, $json_string) or die('Internal Sever Error');
After I got an internal server error, I realized that this is because the $json variable is an array; I need to convert it into a string and then insert it into the file. I first used serialize() but that just inserted some weird stuff into my file. How do I convert the json array into a string before moving it into the file?
Thanks In Advance
Try this piece of code. It doen't use JSON but it still saves data into a file which is split up using tab
<?php
$count=10;//whatever you defined it to
$qa = "";
for ($x=1; $x < $count + 1; $x++) {
$qa .= $_POST["q".$x]."\t".$_POST["a".$x]."\n";
}
$json_file = 'file.txt';
unlink($json_file);
file_put_contents($qa);
?>
<?php
//to retrieve q&a
$qas = file('file.txt',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$qas = explode("\t",$qas);
foreach($qas as $question => $answer)
{
//your code
}
?>
fwrite($handle, $encoded_array) or die('Internal Sever Error');
Related
Like always, I am having issues doing this. So, I have been able to extract images from folders using php, but since it was taking too long to do that, I decided to just extract the names from a text file and then do a while loop and echo the list of results. For example I have a file called, "cats.txt" and inside the data looks like this.
Kitten1.jpg
Kitten2.jpg
Kitten3.jpg
I could easily use an sql or json table to do this, but I am not allowed. So, I only have this.
Now, I have tried doing this, but I get an error.
--- PHP CODE ---
$data = file ("path/to/the/file/cats.txt");
for ($i = 0; $i < count ($data); i++){
$images = '<img src="/kittens/t/$i">';
}
$CatLife = '
Images of our kittens:<br>
'.$images.'
';
I would really appreciate the help. I am not sure of what the error is, since the page doesn't tell me anything. It just doesn't load.
You can try something like this:
$fp = fopen('path/to/the/file/cats.txt', 'r');
$images = '';
while(!feof($fp)) {
$row = fgets($fp);
$images .= '<img src="/kittens/t/'.$row.'">';
}
fclose($fp);
$CatLife = "Images of our kittens:<br>$images";
Maybe you should use the glob php function instead of parsing your txt file.
foreach (glob("path/to/the/file/Kitten*.jpg") as $filename) {
echo "$filename\n";
}
Get used to foreach(). Much easier. Also note that variables like $file in your img tag don't get interpreted in single quotes. I use an array and then implode it:
$data = file ("path/to/the/file/cats.txt");
foreach($data as $file) {
$images[] = '<img src="/kittens/t/'.$file.'">';
}
$CatLife = '
Images of our kittens:<br>
'.implode($images).'
';
You could also just use $images .= '<img src="/kittens/t/$file">'; to concatenate and not need to implode.
$data = file ("path/to/the/file/cats.txt");
$images = '';
for ($i = 0; $i < count ($data); i++){
$images .= '<img src="/kittens/t/$i">');
}
$CatLife = 'Images of our kittens:<br>'.$images.'';
echo $CatLife;
Try this, it stores each image tag into a string and echos it to the page.
I can't seem to find an answer. Is there an easy way to change my array in the code, to an associative array?
NOTE:
-All the variables being assigned are declared already
-It basically creates an array from a csv file called staff data and loops through to find the next empty line then adds that row with data, then re-saves back into the csv file.
My problem is that I cannot figure out in the slightest how to change this array to an associative array that will still work with my code.. Any direction would be greatly appreciated. I hope my problem is clear.
// Grabs the csv file (and its existing data) and makes it into an array so the new data can be added to it.
$StaffDetails = array();
$lines = file('data/StaffData.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$StaffDetails[$key] = str_getcsv($value);
}
//This is a for loop that checks when there is an avaliable line to put the data into. It loops over the lines, until there is an empty spot for the new data //to go into.
//It will not run it if the full name is empty.
for ($i=0; $i<200; $i++) {
if(empty($StaffDetails[$i][0]) == false){ //If its full
}else if (empty($StaffDetails[$i][0]) == true){ //If it is empty
//This prints the details of this staff to that line in the data file. $i is the avaliable line found above.
$StaffDetails[$i][0] = $UserFullName;
$StaffDetails[$i][1] = $UserPhoneNumber;
$StaffDetails[$i][2] = $Gender;
$StaffDetails[$i][3] = $Birthday;
$StaffDetails[$i][4] = $TypeOfWork;
$StaffDetails[$i][5] = $StartingDate;
$StaffDetails[$i][6] = $AnnualLeaveLeft;
$StaffDetails[$i][7] = $SickLeaveLeft;
$StaffDetails[$i][8] = $ID;
$StaffDetails[$i][9] = $NumberOfWorkDaysAWeek;
$StaffDetails[$i][10] = $Monday;
$StaffDetails[$i][11] = $Tuesday;
$StaffDetails[$i][12] = $Wednesday;
$StaffDetails[$i][13] = $Thursday;
$StaffDetails[$i][14] = $Friday;
$StaffDetails[$i][15] = $Saturday;
$StaffDetails[$i][16] = $Sunday;
$StaffDetails[$i][17] = $UserUsername;
$StaffDetails[$i][18] = $UserPassword;
$StaffDetails[$i][19] = $Em1FullName;
$StaffDetails[$i][20] = $Em1PhoneNumber;
$StaffDetails[$i][21] = $Em2FullName;
$StaffDetails[$i][22] = $Em2PhoneNumber;
$i =201;
}
//Below saves the previous data and new changes to the csv file
//This opens the csv file as a write file
$MyCsvFile = fopen('data/StaffData.csv', 'w');
//This takes the array that has had data ddded to it and adds it to the file
foreach ($StaffDetails as $fields) {
fputcsv($MyCsvFile, $fields);
}
//This closes the file
fclose($MyCsvFile);
}
I'm using the following to convert CSV to JSON (https://gist.github.com/robflaherty/1185299). I need to need to modify it so that instead of using the exact file url path, it's pulling the newest file url in the directory as it's "source" in $feed.
Any help would be great! I've tried using the code found here PHP: Get the Latest File Addition in a Directory, but can't seem to figure how modify it so that it would work.
<?php
header('Content-type: application/json');
// Set your CSV feed
$feed = 'http://myurl.com/test.csv';
// Arrays we'll use later
$keys = array();
$newArray = array();
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
// Do it
$data = csvToArray($feed, ',');
// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
//Use first row for names
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
// Add Ids, just in case we want them later
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
// Print it out as JSON
echo json_encode($newArray);
?>
It's a difficult question to answer because there isn't enough detail.
Here are some questions that need answered.
1). Are you creating the csv files that are being read? If you are, you just make sure that the file you want to read is called "latest.csv" and when you go to create "latest.csv" you check for an existing "latest.csv" and rename/archive it first. Your directory then contains archives but the latest one is always of the same name.
2). If you are not creating the csv files then you might want to ask the provider of the csv files if there's a way for you to identify the latest one, as surely, if they are providing them they'd expect to be providing everyone the latest feed and have a mechanism of doing that.
3). If you don't know the provider and want to take a guess, have a look at how the files are named and try to predict the latest one. Eg, if they appear to be including a month and year in them do a file_exists() (if you can) on the predicted next latest file. Again, just a possibility.
Based on your comments, if the files reside on the same server or are accessible on a filesystem that supports the file functions, then:
array_multisort(array_map('filemtime', $files=glob('/path/to/*.csv')), SORT_DESC, $files);
$newest = $files[0];
For remote access you could look at something like this: How can I download the most recent file on FTP with PHP?
Hopefully, I won't be a novice for long. I have a 2-dimensional array (simplified) that I'm trying to work with. Simply pulling out, adding to, and uploading a file record. Can somebody forgive my ignorance and explain what I'm doing wrong?:
<?php
// Updating Current Number of Vendors
$vendorcount = #file_get_contents('../Keys/VendorCount/$v');
if(isset($vendorcount))
{
$new_vendor_number = ($vendorcount + 1);
$n = $new_vendor_number;
}
else
{
$vendorcount = 0;
$new_vendor_number = 1;
$file = '../Keys/VendorCount/$v' ;
file_put_contents($file, $vendorcount) ;
};
//getting record from file
$record = file_get_contents('../Vendors/$vendorlist');
//adding new information to record array
$record[$n] = array($new_vendor_number, $catname);
//uploading updated record
$file = '../Vendors/$vendorlist' ;
file_put_contents($file, $record) ;
?>
You need to use serialize() and unserialize() in order to store an array to a file or restore it from a file. Like this:
$array = array(1,2,3);
// writing to file
file_put_contents('file.txt', serialize($array));
// restoring from file
$array = unserialize(file_get_contents('file.txt'));
This will work with arrays of any dimension.
I'm trying to read a txt file using PHP and then echo the contents of that text file out into JSON format to send back via an AJAX request. This works fine for me when the txt file contains no line-breaks/paragraphs, but not when there is.
Therefore I'm looking for a way to search for line breaks within the text file when it's contents is returned and replace them with a < br > tag to insert into the JSON.
Currently my code looks like this...
$jsonFile = '{';
$projectName = $_POST["project"];
//directories
$videoDir = $_SERVER['DOCUMENT_ROOT'].'/malagnini/projects/'.$projectName.'/video/';
$audioDir = $_SERVER['DOCUMENT_ROOT'].'/malagnini/projects/'.$projectName.'/audio/';
$textData = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/malagnini/projects/'.$projectName.'/description.txt', true);
//add text data to JSON
$jsonFile .= '"text":"'.$textData.'",';
//add video paths to JSON
$j = 1;
if ($dirHandle = opendir($videoDir) ){
while (($file = readdir($dirHandle)) !== FALSE){
if (!is_dir($file)){
$jsonFile .= '"video'.$j.'":"'.$file.'",';
$j++;
}
}
};
//add audio paths to JSON
$jsonFile .= '"audio": {';
$i = 1;
if ($dirHandle = opendir($audioDir) ){
while (($track = readdir($dirHandle)) !== FALSE){
if (!is_dir($track)){
$jsonFile .= '"track'.$i.'":"'.$track.'",';
$i++;
}
}
};
//echo JSON
$jsonFile = chop($jsonFile, ",");
$jsonFile .= '} }';
echo $jsonFile;
So the text data is read in through the var &textData, but when it outputs to JSON it is not valid JSON when there are line breaks in the txt file.
Therefore I'm looking for a way to search for line breaks within the
text file when it's contents is returned and replace them with a < br > tag to insert into the JSON.
I think this is what you need :
http://php.net/manual/fr/function.nl2br.php
you shouldn't compile json manually, why not build an array with the desired properties and then json_encode it?
Therefore you wouldn't have to bother at all about the inner composition of the strings.
Easiest way to convert newline character to break tag, is to simply run the string through nl2br()