function readWrite() {
$fileReader = fopen('file.txt', 'r') or die("ERROR: File not found");
$fileWriter = fopen('filewr.txt', 'w') or die ("ERROR: Write File not
found");
$totalDaysArr= array();
$monthNumArr= array();
$monthArr= array();
$row= file("file.txt");
while($row = fgets($fileReader, 4096)) {
list($monthNumArr[], $monthArr[], $totalDaysArr[]) = explode(",", $row);
}
for($x = 11; $x >= 0; $x--)
{
$table = explode(",", $monthNumArr[$x]);
fwrite($fileWriter, $row[$x]);
}
fclose($fileWriter);
}
I'm a beginner at PHP, so this is what I have so far. My objective is to make a function that will read a file called file.txt and then write it in reverse using arrays. I'm not sure what I am doing wrong here.
These are the requirements:
This function should use PHP array to store records (each line is a "record").
This function should use a PHP Loop to walk through the months names array and generate HTML5/CSS to display the table.
Create a function that writes the text file filewr.txt (reverse order).
This function should use PHP for loop to walk through the array in reverse order and write each array entry (line/record) to the filewr.txt file.
and also the txt file looks like this:
1,January,31
2,February,28
3,March,31
4,April,30
5,May,31
6,June,30
7,July,31
8,August,31
9,September,30
10,October,31
11,November,30
12,December,31
Why use fileReader when you decide to read the data with file("file.txt"); in the end?
The writing process is quite messed up fwrite($fileWriter, $row[$x]) is quite possibly the place where the error comes from: don't you aim to write that table to your file instead of a row from the original input file?
Addition
#Aureliux:
What you want to to is generating a HTML string.
Therefore, lets start with $table='<table>' and put this definition before the loop.
After the loop you add the tables closing tag: $table.='</table>'
The magic happens in between:
For each record you create the corresponding HTML representation.
$table.='<tr><td>'.$monthNumArr.'</td><td>'.$monthArr.'</td><td>'.$totalDaysArr.'</td></tr>'.
Finaly you move the write command after the loop and write the generated Table Markup to your output file.
What you will end up with looks like
function readWrite() {
$fileWriter = fopen('filewr.txt', 'w') or die ("ERROR: Write File not
found");
$totalDaysArr= array();
$monthNumArr= array();
$monthArr= array();
$row= file("file.txt");
while($row = fgets($fileReader, 4096)) {
list($monthNumArr[], $monthArr[], $totalDaysArr[]) = explode(",", $row);
}
$table='<table>';
for($x = 11; $x >= 0; $x--)
{
$table.='<tr><td>'.$monthNumArr.'</td><td>'.$monthArr.'</td><td>'.$totalDaysArr.'</td></tr>';
}
$table.='</table>';
fwrite($fileWriter, $table);
fclose($fileWriter);
}
I have no idea why you would need the reverse loop, but actually, you could achieve the same result with less effort:
function readWrite() {
$row= file("file.txt");
$table='<table>';
for($x = 11; $x >= 0; $x--)
{
$table.='<tr><td>'.implode('</td><td>', explode(',',$row[$x])).'</td></tr>';
}
$table.='</table>';
file_put_contents('file.txt', $table);
}
I did not test it. But the idea should be clear.
Personally, I would agree with #Alive to Die. His approach is the most straight forward.
Related
We have made an array from a text file full of numbers separated by commas, each new line is a new part of the array. (we are not allowed to use explode for this)
We are trying to create a transpose_matrix function to 'transpose' the array now.
Using tutorials on the internet, this is what we have come up with so far, but it doesn't work :(
$myfile = fopen("text1.txt", "r") or die("Unable to open file!");
//echo fread($myfile,filesize("text1.txt"));
$file1 = file("text1.txt");
$store1 = array();
for ($a = 0; $a<count($file1); $a++)
{
array_push($store1, $file1[$a]);
}
for ($k = 0; $k<count($store1); $k++)
{
echo "Line $store1[$k] <br/> END <br/>";
}
function transpose($store1) {
$file1 = file("text1.txt");
$store1 = array();
if (count($store1) == 0) // special case: empty matrix
return array();
else if (count($store1) == 1) // special case: row matrix
return array_chunk($store1[0], 1);
function myCallbackMethod() {
var_dump ($store1);
}
array_unshift($store1, NULL); // the original matrix is not modified because it was passed by value
return call_user_func_array('myCallbackMethod',$store1);
}
transpose($store1);
fclose($myfile);
}
Try reading with fscanf().
something like
fscanf($file_link, '%s\n', $temp);
array_push($array, $temp);
should work.
Sukhdev Mohan
I'm having an issue with a memory leak in this code. What I'm attempting to do is to temporarily upload a rather large CSV file (at least 12k records), and check each record for a partial duplication against other records in the CSV file. The reason why I say "partial duplication" is because basically if most of the record matches (at least 30 fields), it is going to be a duplicate record. The code I've written should, in theory, work as intended, but of course, it's a rather large loop and is exhausting memory. This is happening on the line that contains "array_intersect".
This is not for something I'm getting paid to do, but it is with the purpose of helping make life at work easier. I'm a data entry employee, and we are having to look at duplicate entries manually right now, which is asinine, so I'm trying to help out by making a small program for this.
Thank you so much in advance!
if (isset($_POST["submit"])) {
if (isset($_FILES["sheetupload"])) {
$fh = fopen(basename($_FILES["sheetupload"]["name"]), "r+");
$lines = array();
$records = array();
$counter = 0;
while(($row = fgetcsv($fh, 8192)) !== FALSE ) {
$lines[] = $row;
}
foreach ($lines as $line) {
if(!in_array($line, $records)){
if (count($records) > 0) {
//check array against records for dupes
foreach ($records as $record) {
if (count(array_intersect($line, $record)) > 30) {
$dupes[] = $line;
$counter++;
}
else {
$records[] = $line;
}
}
}
else {
$records[] = $line;
}
}
else {
$counter++;
}
}
if ($counter < 1) {
echo $counter." duplicate records found. New file not created.";
}
else {
echo $counter." duplicate records found. New file created as NEWSHEET.csv.";
$fp = fopen('NEWSHEET.csv', 'w');
foreach ($records as $line) {
fputcsv($fp, $line);
}
}
}
}
A couple of possibilities, assuming the script is reaching the memory limit or timing out. If you can access the php.ini file, try increasing the memory_limit and the max_execution_time.
If you can't access the server settings, try adding these to the top of your script:
ini_set('memory_limit','256M'); // change this number as necessary
set_time_limit(0); // so script does not time out
If altering these settings in the script is not possible, you might try using unset() in a few spots to free up memory:
// after the first while loop
unset($fh, $row);
and
//at end of each foreach loop
unset($line);
I have been researching fgetcsv() and have the following working code:
$file = fopen($pathToCsv,"r");
$data = array();
while(! feof($file))
{
array_push($data, fgetcsv($file));
}
fclose($file);
However, when I try to adapt this to dynamically accept an unknown number of csv files stored into an array, things cease to work:
$year = $_POST['year'];
$m = "maths".$year;
$sheets = $$m; //an array containing between 5 an 8 paths to csv and other info
$data = array();
function ArrayFromCsv($file, $i) {
while(! feof($file))
{
array_push($data[$i], fgetcsv($file)); //line 15
}
fclose($file);
}
for ($i = 0; $i < count($$m); $i++){
array_push($data, array());
$x = fopen($sheets[$i]['csv'],'r');
ArrayFromCsv($x, $i);
}
I get: Warning: array_push() expects parameter 1 to be array, null given in ... on line 15
I'm not how to research this further. Is there a better way or obvious mistake? I've tried a number of methods.
You dont have access to the global $data variable inside of the function ArrayFromCsv. You either need to use "global $data" inside the function, which is bad, so DON'T
Or you could create a temporary array inside the function, which you return when the function ends and put the returned value from the function into $data[$i]. Also you should not open a file outside of a function and close it inside of a function. That could lead to undefined behaviour someday when your code gets bigger.
function ArrayFromCsv($file, $i) use (&$data) {
while(! feof($file))
{
array_push($data[$i], fgetcsv($file)); //line 15
}
fclose($file);
}
I had a script called CSVimporter V3 for PHP that I used to run on a website and it worked fine. A couple of years later I've now dug out the same script to use on another project, all works okay except the CSV files are being read as one long line, as opposed to header row and multiple lines.
Here is part of the script.
Any ideas why it would be being read as a long line?
<?php
// Reference session variable for short-hand
$f = &$_SESSION['csv_file'];
// Open file - fp = file pointer
if (!$fp = #fopen($f, 'r')) {
error(L_ERROR_PREVIEW_NO_FILE);
} else {
// Array to store each row to be inserted
$batch = array();
// Row counter
$rc = 0;
// Work out starting row
switch ($_SESSION['csv_first_row']) {
case 'data':
$start_row = 0;
break;
default:
$start_row = 1;
}
// Get contents, while below preview limit and there's data to be read
while ($data = fgetcsv($fp, 1024, delimiter_to_char($_SESSION['csv_delimiter']))) {
if ($rc < $start_row) {
// Incremement counter
$rc++;
// Go to next loop
continue;
} else {
// Array to store data to be inputted
$values = array();
// Loop data
for ($i = 0; $i < count($data); $i++) {
// If data is wanted, put data into array
if (array_key_exists($i, $column_index)) {
$values[$column_index[$i]] = $data[$i];
}
}
// Sort array into correct order by index
ksort($values);
// Join values together and store in array
$batch[] = '("' . implode('", "', str_replace('"', '\"', $values)) . '","'.$accti.'","'.$impt.'")';
}
}
}
// Close the file
fclose($fp);
I added this at the top of the code and it all works now!
ini_set('auto_detect_line_endings', true);
I have a filter bad words codes below
I want to replace this ARRAY with the .txt file so that I can put all the bad words into the txt file or is there any way to use MYSQL database to store the badwords and then call from there ?
FUNCTION BadWordFilter(&$text, $replace){
$bads = ARRAY (
ARRAY("butt","b***"),
ARRAY("poop","p***"),
ARRAY("crap","c***")
);
IF($replace==1) { //we are replacing
$remember = $text;
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
$text = EREGI_REPLACE($bads[$i][0],$bads[$i][1],$text); //replace it
}
IF($remember!=$text) RETURN 1; //if there are any changes, return 1
} ELSE { //we are just checking
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
IF(EREGI($bads[$i][0],$text)) RETURN 1; //if we find any, return 1
}
}
}
$qtitle = BadWordFilter($wordsToFilter,1);
I just developed a function that can filter out the bad words
function hate_bad($str)
{
$bad = array("shit","ass");
$piece = explode(" ",$str);
for($i=0; $i < sizeof($bad); $i++)
{
for($j=0; $j < sizeof($piece); $j++)
{
if($bad[$i] == $piece[$j])
{
$piece[$j] = " ***** ";
}
}
}
return $piece;
}
and call it like this
$str = $_REQUEST['bad']; //'bad' is the name of the text field here
$good = hate_bad($str);
if(isset($_REQUEST['filter'])) //'filter' is the name of button
{
for($i=0; $i < sizeof($good); $i++)
{
echo $good[$i];
}
}
Yes make a file like bad_words.txt with entries like (note each word combo is on a separate line):
butt,b***
poop,p***
crap,c***
Then read that file into an array like so:
$file_array = file('/path/to/bad_word.txt',FILE_IGNORE_NEW_LINES);
Then to create an array like your $bads array do this:
$bads = array();
foreach ($file_array as $word_combo) {
$bads[] = explode(',', $word_combo);
}
Hope this helps.
You can do either...
You can use something like file_get_contents() to read in from a file, or use a MySQL API to query your database for bad words.
Do you have a database schema set up? Also, eregi_replace() is deprecated. Use preg_replace() instead.
You could use MYSQL.
Just have a table with two columns: the word and the replacement.
Then in your code, you will need to connect to the database and read in each row. But you can then store each row in an array.
The result would be very similar to your current array structure.
To connect to a database, use the tutorial below.
http://www.homeandlearn.co.uk/php/php13p1.html