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?
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+')
I would like to be able to edit a config file for a server application using php. The config file is as follows:
include=sc_serv_public.conf
streamid_2=2
streampath_2=/relay
streamrelayurl_2=http://<full_url_of_relay_including_port>
;allowrelay=0
;allowpublicrelay=0
I would like to edit the line:
streamrelayurl_2=http://<full_url_of_relay_including_port>
and then save the file.
I am currently using:
$data = file_get_contents("sc_serv.conf"); //read the file
$convert = explode("\n", $data); //create array separate by new line
to open the file, but now I dont know how to edit it.
As an alternative, you could just use file() instead. This just loads it up into array form, no need to explode. Then after that, you just loop the elements, if the desired needle is found, overwrite it, the write the file again:
$data = file('sc_serv.conf', FILE_IGNORE_NEW_LINES); // load file into an array
$find = 'streamrelayurl_2='; // needle
$new_value = 'http://www.whateverurl.com'; // new value
foreach($data as &$line) {
if(strpos($line, 'streamrelayurl_2=') !== false) { // if found
$line = $find . $new_value; // overwrite
break; // stop, no need to go further
}
}
file_put_contents('sc_serv.conf', implode("\n", $data)); // compound into string again and write
You can use file() to read the file content to an array, then you can iterate trough the array with foreach() searching with the strstr() function the line that have your URL (in this case is in the var $id_change) and change the value. Then as you found what you needed, you end the foreach() with break. And make your string to save in the file with implode() and save the string to the config file with file_put_content().
See the code:
<?php
$new_url = 'http://www.google.com';
$id_change = 'streamrelayurl_2';
$file = "sc_serv.conf";
$data = file($file); //read the file
foreach($data as $key => $value) {
if(strstr($value, $id_change)) {
$info = $id_change . '=' . $new_url . "\n";
$data[$key] = $info;
break;
}
}
$data = implode("", $data);
file_put_contents($file, $data);
?>
Output:
include=sc_serv_public.conf
streamid_2=2
streampath_2=/relay
streamrelayurl_2=http://www.google.com
;allowrelay=0
;allowpublicrelay=0
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);
I have this script that I did, it basically grabs all the files in my "logs" folder and merge them all in one array file, my only problem is that, sometimes the script breaks if there is blank line or empty line! how can I tell it to automatically skip blank empty lines and go to next? blank lines are not necessarily at the top or bottom! could be in the middle of the csv file
<?php
$csv = array();
$files = glob('../logs/*.*');
$out = fopen("newfile.txt", "w");
foreach($files as $file){
$in = fopen($file, "r");
while (($result = fgetcsv($in)) !== false)
{
$csv[] = $result;
}
fclose($in);
fclose($out);
}
print json_encode(array('aaData' => $csv ));
?>
As you can read in the documentation for fgetcsv():
A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.
Checking for that before adding it to your data array should be sufficient:
while (($result = fgetcsv($in)) !== false) {
if (array(null) !== $result) { // ignore blank lines
$csv[] = $result;
}
}
This works 100% tested, simplest way. The explanation is that blank lines make fgetcsv return a non-empty array with just a null element inside.
if ($result[0] == NULL)
continue;
In short
$csv = array_map('str_getcsv', file($file_path, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES));
Explanation
file reads the content of the file into an array. The FILE_SKIP_EMPTY_LINES will skip the empty lines in the file.
array_map will apply the function str_getcsv on each element of the array. str_getcsv will parse the string input for fields in
csv format and return an array containing the fields.
Read more about str_getcsv
Read more about file
Read more about array_map