I'm trying to execute the code below and I keep on getting a message reading killed when I load the file in my terminal. I'm aware that I'm using lots of memory, so I set the memory limit to the maximum amount allowed on apache. I have a text file called codes.txt that contains a list of numbers from 0 to 1000000. I need to randomize the occurrence of these numbers and then write the new order of them to a new text file. Then, I need to store the new occurrence of them in an array.
ini_set('memory_limit', '2048M');
// Get all of the values from the .txt file
// and store them in an array
$file = fopen("codes.txt", "r");
$codes = array();
while(!feof($file)) {
$codes[] = trim(fgets($file));
}
fclose($file);
// Randomize the elements in the array
shuffle($codes);
// Write each element in the shuffled array to a new .txt file
$new_file = fopen("new_codes.txt", "w");
for($i=0;$i<1000000;$i++) {
fwrite($new_file, $codes[$i].PHP_EOL);
}
fclose($new_file);
// Put all of the new elements into a new array
$new_file = fopen("new_codes.txt", "r");
$code = array();
while(!feof($new_file)) {
$code[] = trim(fgets($new_file));
}
print_r($code);
Don't worry about a new array, $codes already has them. If you need to close, reopen the file and read them into a new array, and memory is the issue, then kill the old array first by using unset($codes) before opening the file.
ini_set('memory_limit', '2048M');
// Get all of the values from the .txt file
// and store them in an array
$file = fopen("codes.txt", "r");
$codes = array();
while (!feof($file)) {
$codes[] = trim(fgets($file));
}
fclose($file);
// Randomize the elements in the array
shuffle($codes);
// Write each element in the shuffled array to a new .txt file
$new_file = fopen("new_codes.txt", "w");
foreach($codes as $k => $v){
fwrite($new_file, $v.PHP_EOL);
}
fclose($new_file);
Related
I am making a redeem key page for educational purposes with PHP just to see what it is capable of. I am storing the keys in a txt file as such:
key1
key2
And so on.
I have tried the following to loop through the txt file, insert the values into and array and work off of there. Here is what I have:
$gkey = $_GET["key"];
$file = fopen("./generatedkeys.txt", "a");
$generatedk = array();
// generate table from data in txt file
while(! feof($file)) {
$generatedk[] = fgets($file);
}
foreach ($generatedk as $key){
if ($key == hash("sha256", $gkey)){
// Removing of key from data in txt file
$contents = file_get_contents($file);
$contents = str_replace($key, '', $contents);
file_put_contents($file, $contents);
fclose($file);
$accfile = fopen("./accs.txt", "a");
fwrite($accfile, hash("sha256", $key).",".hash("sha256", $hwid)."\n");
break;
}
}
The code above however doesn't seem to be working. The key is simply not detected and not removed from generatedkeys.txt. (Not sure if there is any errors since I cannot see any).
Is there any obvious mistakes?
Any help is appreciated. Thank you.
I think this should make the process simpler, using file to read the whole file in one go into an array and then using array_search() to find if the key exists (it returns false if not found, so !== false).
Then if found, it just appends the used key to the other file, unsets the array entry for the key and overwrites the original file...
$gkey = $_GET["key"];
$generatedk = file("./generatedkeys.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ( ($entry = array_search(hash("sha256", $gkey), $generatedk)) !== false ) {
// Add key used, with whatever content you want
file_put_contents("./accs.txt", $gkey.PHP_EOL, FILE_APPEND);
// Remove found key from list in input file
unset($generatedk[$entry]);
// Overwrite input file with adjusted array
file_put_contents("./generatedkeys.txt", implode(PHP_EOL, $generatedk));
}
Your code will make some empty lines when erases key from file.
And you passed return value of fopen() as a parameter of file_get_contents(). the return value is resource on file, but file_get_contents() needs string(file path).
You can check following.
$gkey = $_GET["key"];
$file_path="./generatedkeys.txt";
$file = fopen($file_path, "a");
$generatedk = array();
// generate table from data in txt file
while(! feof($file)) {
$generatedk[] = fgets($file);
}
fclose($file);
for($i=0; $i<count($generatedk); $i++){
$key=$generatedk[$i];
if ($key == hash("sha256", $gkey)){
// Removing of key from data in txt file
array_splice($generatedk, $i, 1);
file_put_contents($file_path, implode("\n", $generatedk));
$accfile = fopen("./accs.txt", "a");
fwrite($accfile, hash("sha256", $key).",".hash("sha256", $hwid)."\n");
fclose($accfile);
break;
}
}
I hope it will be working well.
Thanks.
Trying to get multiple pages of an API returning JSON into one CSV file. Currently it will be sufficient to set the maximum amount of pages it will loop through to 120.
This is the first request without any loop which creates a working CSV file (output.txt).
<?php
$pageNo = "1";
$jsonString = file_get_contents("http://api.domain.com/apikey/?
name1=value1&name2=value2&pageNo=$pageNo");
$jsonDecoded = json_decode($jsonString, true);
$csvHeader=array();
$csvData=array();
$csvFileName = 'output.txt';
$fp = fopen($csvFileName, 'w');
$counter=0;
foreach($jsonDecoded["result"]["items"] as $key => $value)
{
jsontocsv($value);
if($counter==0)
{
fputcsv($fp, $csvHeader, ';');
$counter++;
}
fputcsv($fp, $csvData, ';');
$csvData=array();
}
fclose($fp);
function jsontocsv($data)
{
global $csvData,$csvHeader;
foreach($data as $key => $value)
{
if(!is_array($value))
{
$csvData[]=$value;
$csvHeader[]=$key;
}
else
{
jsontocsv($value);
}
}
}
?>
I'm guessing this should be in a while loop, with something like ++$pageNo at the end, updating the value. However all previous attempts have resulted in the file being overwritten each time and only the last page being written into the file. How can I add stuff to the CSV each time it loops? Ideally, though, each time the entire script runs (once per day), the entire CSV file will be replaced with the updated values.
Thanks
you are opening the file in write mode, which places the pointer to the beginning of the file (fopen($csvFileName, 'w')), this is why it gets overridden.. try using append mode, it should place the pointer to the end.. also, if you want to create the file if it does not exist, use the plus sign like this: fopen($csvFileName, 'a+')
english, lang1, lang2
rat, rat_lang1, rat_lang2
ball, ball_lang1, ball_lang2
air, air_lang1, air_lang2
If I have this text file I read in php, how can I sort it starting the second line, the first line being the heading of the file. So that the file will print out like..
english....
air....
ball...
rat....
I read the file using fopen, put it in $content using fread, used explode with new line. I can see the array of lines but cannot figure out how to sort it. Any suggestions would be appreciated.
Much of this solution was answered within the comments in response to your question. All put together you're looking for something like:
<?php
$f = file("text.txt"); //read the text file into an array
$newf = fopen("newtext.txt", "w+"); //open another file
$header = $f[0]; //store the first element of the array as $header
echo $header."<br>"; //and echo the header
fwrite($newf, $header); //write the header to the new file
array_shift($f); //then remove the first element of the array i.e. the header
sort($f); //sort the array (no flag param = alphabetical sort)
foreach($f as $line){ //loop through the sorted array
echo $line."<br>"; //print each element as it's own line
fwrite($newf, trim($line)."\n"); //write other elements to new file on own line
}
fclose($newf); //close the file
?>
Try this:
$data = trim(file_get_contents('sort_test.txt'));
$data = explode("\n", $data);
$array_order = array();
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation, "w");
for ($i = 0; $i < count($data); $i++) {
($i > 0) ? $array_order[$i] = $data[$i] : fwrite($file, $data[0]);
}
sort($array_order);
$data = implode("\n", $array_order);
fwrite($file, $data);
fclose($file);
echo 'file created - location::' . $fileLocation;
Output myfile.txt
english, lang1, lang2
air, air_lang1, air_lang2
ball, ball_lang1, ball_lang2
rat, rat_lang1, rat_lang2
Maybe the new file (myfile.txt) will needs write permission to the directory you are writing to , in my case the file has been stored into C:/.../htdocs/myfile.txt
I have a CSV file which is generated dynamically. I want to remove the first line of CSV and then save it again.
I have googled and was able to get first line of csv but the part of writing it again after removing is where I am stuck.
Here is example
line1,data1
line2,data2
line3,data3
What I want to acheive
line2,data2
line3,data3
That is first line removed and file saved again
Here is my code
$file = fopen('words.csv', 'r');
$data = fgetcsv($file,10000,",");
$data = array_shift($data);
$file = fopen('words.csv', 'w');
fputcsv($file,$data,",");
fclose($file);
I get this:
! ) Warning: fputcsv() expects parameter 2 to be array, string given in C:\wamp\www\scrape\test.php on line 7
And output file is empty.
Ahmar
// Read the file
$file = fopen('words.csv', 'r');
// Iterate over it to get every line
while (($line = fgetcsv($file)) !== FALSE) {
// Store every line in an array
$data[] = $line;
}
fclose($file);
// Remove the first element from the stored array / first line of file being read
array_shift($data);
// Open file for writing
$file = fopen('words.csv', 'w');
// Write remaining lines to file
foreach ($data as $fields) {
fputcsv($file, $fields);
}
fclose($file);
You have some errors in your code. The first one is that fgetcsv function only gets one line so if you want to extract all the lines you need a loop. The same happens with fputcsv function.
The other one is that array_shift function returns the shifted value so you are assigning to $data the string you don't need.
So, I think your code must be like:
$file = fopen('words.csv', 'r');
$data=array();
while (($data_tmp = fgetcsv($file, 1000, ",")) !== FALSE) {
$data[] = $data_tmp;
}
fclose($file);
array_shift($data);
$file = fopen('words.csv', 'w');
foreach($data as $d){
fputcsv($file,$d);
}
fclose($file);
I am using this function to generate CSV file
function array_to_csv($input, $delimeter=',', $linebreak="\n", $enclosure='"') {
if (!is_array($input))
die("Please provide an array of data.");
// $keys = array_keys($input);
$values = array_values($input);
foreach ($values as $k => $v) {
// Not refactored
$values[$k] = $enclosure.str_replace($enclosure, $enclosure.$enclosure, $v).$enclosure;
}
//print implode($delimeter, $keys);
//print $linebreak;
//print implode($delimeter, $values);
$write = implode($delimeter, $values);
$file='abc.csv';
$fp = fopen($file, "w");
fwrite($fp, $write);
fclose($fp);
}
In php I call this function as:
array_to_csv($title, $delimeter=',', $linebreak="\n", $enclosure='"');
$title is my array I am passing to the function. Till this point, everything is okay, file is successfully saved.
Now I want to writing CSV file using same function while calling more than 1 function such that:
1: first element of array1 is written in file
2: first element of array2 is written in file
3: first element of array3 is written in file
How can I accomplish this task? Have any one idea about it?