How to Create a CSV file using PHP (and upload it) - php

For example, I have a variable "$foo" that includes all the data which I want to show in the CSV:
$foo = "some value,another value,last value";
My goal is to:
Create a CSV file named "some.csv" whose contents are equal to $foo
Upload "some.csv" to my server.
How can this be done?
Update: Here's the exact code that worked for me.
$foo = "some value,another value,last value";
$file = 'some_data.csv';
file_put_contents($file, $foo);

Number 1:
file_put_contents("foobar.csv", $yourString);
Number 2:
$c = curl_init("http://"...);
curl_setopt($c, CURLOPT_POSTFIELDS, array('somefile' => "#foobar.csv"));
$result = curl_exec($c);
curl_close($c);
print_r($result);
note the # before the filename

See
fputcsv()
If $foo is already csv-formatted. You can use file_put_contents()
You don't specify the upload method. Here is an example using ftp (UNSECURE):
$foo = '...csv data...';
$username = "myUser";
$password = "myPassword";
$url = "myserver.com/file.csv";
$hostname= "ftp://$username:$password#$url";
file_put_contents($hostname, $foo);

If you already have the variable with all the data you can use file_put_contents to save it as a csv

How to upload CSV file using PHP (Working Code)
Query Library
<?php
class query{
function mysql_query_string($string){
$enabled = true;
$htmlspecialchars = false; # Convert special characters to HTML entities
/****************************************************************
The translations performed are:
'&' (ampersand) becomes '&'
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set.
''' (single quote) becomes ''' only when ENT_QUOTES is set.
'<' (less than) becomes '<'
'>' (greater than) becomes '>'
*****************************************************************/
if($htmlspecialchars){
# Convert special characters to HTML entities
$string = htmlspecialchars($string, ENT_QUOTES);
}
else{
/****************************************************************
'"' (double quote) becomes '"'
''' (single quote) becomes '''
****************************************************************/
//$string = str_replace('"',""",$string);
//$string = str_replace("'","'",$string);
}
if($enabled and gettype($string) == "string"){
# Escapes special characters in a string for use in a SQL statement
return mysql_real_escape_string(trim($string));
}
elseif($enabled and gettype($string) == "array"){
$ary_to_return = array();
foreach($string as $str){
$ary_to_return[]=mysql_real_escape_string(trim($str));
}
return $ary_to_return;
}
else{
return trim($string);
}
}
}
?>
Call Csv Method
public function csvFileSubmitData(){
$this->load->library('query');
$query=new query();
$root = DIR_PATH.'public/administrator/csv/';
$fileToUpload= (isset($_FILES['fileToUpload']) and $_FILES['fileToUpload']['size'] > 0 and
$_FILES['fileToUpload']['error'] == 0) ? $_FILES['fileToUpload'] : "";
if(is_array($fileToUpload)){ # CHECK UPLOADED FILE 1 FOR VALIDATION
$fileToUpload['name'] = str_replace(" ","_",$fileToUpload['name']);
$fileToUpload['name'] = str_replace("&","and",$fileToUpload['name']);
# CHECK FILE TYPE IF IT IS IMAGE JPG,GIF,PNG ETC
$fnarr = explode(".", $fileToUpload['name']);
}
$rand = rand(1000,10000);
$filecsv = $rand."_".$fileToUpload['name'];
$file1 = $root.$filecsv;
move_uploaded_file($fileToUpload['tmp_name'],$file1);
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = $file1;
$addauto = 0;
$save = 0;
$outputfile = "output.sql";
if(!file_exists($csvfile)) {
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 1;
$queries = "";
$linearray = array();
$values = "";
$m =0;
$linestext = split($lineseparator,$csvcontent);
foreach($linestext as $line){
if($m++==0){
continue;
}
$lines++;
$line = trim($line," \t");
if($line == ''){
break;
}
$linearray = explode($fieldseparator,$line);
$topicname = $linearray[0];
$question = $linearray[1];
$answer1 = $linearray[2];
if(isset($linearray[1]) and $linearray[1] != ''){
$topicname = $query->mysql_query_string($linearray[0]);
$question = $query->mysql_query_string($linearray[1]);
$answer_type = $query->mysql_query_string($linearray[2]);
}
//Save Csv data in your table like this
//query(insert into topics SET `topic`='".$topicname."',`question`='".$question."');
}}
If you are using Codeignitor Framework so this code is too easy to integrate ,No hard&fast rule you can also use this code plain PHP as well as .....
Thanx
AbdulSamad

To create the CSV you would need to break your string into an array, then loop through it. After that you can save the file to any directory the web server account has access to on your server. Here is an example ...
//variables for the CSV file
$directory = '/sampledir/';
$file = 'samplefile.csv';
$filepath = $directory.$file;
//open the file
$fp = fopen("$filepath",'w+');
//create the array
$foo = "some value,another value,last value";
$arrFoo = explode(',',$foo);
//loop through the array and write to the file
$buffer = '';
foreach($arrFoo AS $value) {
$buffer .= $value."\r\n";
}
fwrite($fp,$buffer);
//close the file
fclose($fp);
Your file will now be written to the directory set in $directory with the filename set in $file.
-Justin

Related

php unable to open file when open and write into file

i try to read a text file line by line and if any line contain "/" then i need to write them into separate file.
example line
CA,T2B,Calgary (Forest Lawn / Dover / Erin Woods),Alberta,AB,Calgary,,,,51.0209,-113.981,6
i need to write this as 4 lines, like
CA,T2B,Calgary,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Forest Lawn ,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Dover,Alberta,AB,Calgary,,,,51.0209,-113.981,6
CA,T2B, Erin Woods,Alberta,AB,Calgary,,,,51.0209,-113.981,6
what i've tried so far is
$file = fopen("test.txt", "r");
while (!feof($file)) {
$my_string = fgets($file);
$special_chars = array("/");
if (array_intersect(str_split($my_string), $special_chars)) {
echo fgets($file) . "<br />";
$myfile = fopen("fileWithFL.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
fclose($myfile);
}else{
echo fgets($file) . "<br />";
$myfile = fopen("fileWithoutFL.txt", "w") or die("Unable to open file!");
fwrite($myfile, fgets($file));
fclose($myfile);
}
}
fclose($file);
[
file i get from "CA.zip"
how can i do this?
thank you!
You're repeatedly opening and closing fileWithFL.txt and fileWithoutFL.txt, which is inefficient. Better to just open them once before you loop through the input file.
You're also using fgets(), which makes it difficult to parse the input file. Since the input file seems to be in CSV format, you should use fgetcsv().
As for detecting rows that contain multiple cities, I'm looking for the presence of /, splitting on ( or /), removing any trailing ), and trimming the resulting name. That should give you all the cities in a neat array.
$file = fopen("test.txt", "r");
$file_with_fl = fopen("fileWithFL.txt", "w+");
$file_without_fl = fopen("fileWithoutFL.txt", "w+");
while ($a = fgetcsv($file)) {
if ( FALSE == strpos( $a[2], '/' ) ) {
fputcsv( $file_without_fl, $a );
} else {
$cities = preg_split( '/[\(\/]/', $a[2] ); // Split on '(' and '/'
foreach ( $cities as $city ) {
$city = trim(preg_replace('/\)/', '', $city)); // Remove trailing ')' and trim leading and trailing spaces
$a[2] = $city;
fputcsv( $file_with_fl, $a );
}
}
}
Checking for failure of fopen() and fputcsv() left as an exercise for the reader.
You can use file_put_contents(file, string, FILE_APPEND) to add a line to the end of a file.
The rest is just processing the Calgary (Forest Lawn / Dover / Erin Woods) part of your string.
$string = 'CA,T2B,Calgary (Forest Lawn / Dover / Erin Woods),Alberta,AB,Calgary,,,,51.0209,-113.981,6';
//test if string needs processing
//if not, write straight to new file
if(strpos($string,'/') === false){
file_put_contents("fileWithoutFL.txt" , $string , FILE_APPEND);
}
//process
else{
//get all the parts split by comma
//$parts[2] is the one you need processing
$parts = explode(',',$string);
//clean up $part[2], replacing ( , ) with *
//then split on the *
$com=explode('*',str_replace(['(','/',')'],'*',$parts[2]));
//loop $com, creating new arrays by replacing $part[2] in the original array
foreach($com as $val){
if($val == '')continue;
//replace $part[2] cleaning up spaces
$parts[2] = trim($val);
//make a new line
$write = implode(',',$parts);
//write to the new file
file_put_contents("fileWithoutFL.txt" , $write , FILE_APPEND);
}
}
Now you can read every line of the original file and output to the new file. (Tip: use SplFileObject)
$file = new SplFileObject("fileWithFL.txt");
while (!$file->eof()) {
$string = $file->fgets();
// ... process here with previous code
}
$file = null;
Not the best answer but its works
$line = file_get_contents("test.txt");
$body = "";
if(false !== strpos($line,"/")) {
$split = preg_split("/[()]+/", $line,-1, PREG_SPLIT_NO_EMPTY);
$contains = explode("/",$split[1]);
$last = explode(",",$split[0]);
$lastvalue = end($last);
$search = array_search($lastvalue,$last);
unset($last[$search]);
$merge = implode(", ", $last);
$body .= $merge . $split[2] . " ";
foreach($contains as $contain) {
$body .= $split[0] . "," . $contain . $split[2] . " ";
}
if(file_put_contents("fileWithFL.txt",$body) !== false) {
echo $body;
} else {
echo "failed";
}
} else {
if(file_put_contents("fileWithoutFL.txt",$line) !== false) {
echo $line;
} else {
echo "failed";
}
}
Output :
CA, T2B,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary ,Forest Lawn ,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary , Dover ,Alberta,AB,Calgary,,,,51.0209,-113.981,6 CA,T2B,Calgary , Erin Woods,Alberta,AB,Calgary,,,,51.0209,-113.981,6

How can i add a number to a file name in php

Goodevening to everyone, how can i add a number to a file name in php.
Let me explain; I want to save a file using a dropzone but i want to rename the file if it exist in the folder.
I've written down this code but the regex doesn't work and also if it's possible to insert the number before the extension of the file like google chrome does.
if(file_exists($target_file)){
if(preg_match_all($target_file, "'('[0-9]{1,}')'")==false){
$target_file= $target_path."(1)".$name;
}else{
$pos=preg_match_all($target_file, "'('[0-9]{1,}')'");
$pos=$pos++;
$pos1=strpos($pos, $target_file, ")");
$pos1=$pos1-$pos;
$num=substr($target_file, $pos, $pos1);
$num = (int)$num;
$num =$num++;
$sostituisci="(".$num.")";
$target_file=preg_replace("'('[0-9]{1,}')'", $sostituisci, $target_file);
}
}
$name is the name of the file i want to save with the extension
the first $target_file of the code contain the full path + the name of the file
$target_file is a sting like /dropzone/upload/filename.txt and $name is a string like filename.txt. If the $targetfile exist i would to rename the $name like filename(1).txt or filename(2).txt and so on
also other solutions are accepted like a js library.
I assume you are referring to this set of code here.
if(preg_match_all($target_file, "'('[0-9]{1,}')'")==false){
$target_file= $target_path."(1)".$name;
}
insert the number before the extension of the file
EDIT: Use explode() and re-format the ext.
EXAMPLE:
$target_path = "/assets/imgages/";
$name = 'img.jpg';
$name = explode('.', $name);
$format = $name[0].'(1).'.$name[1];
$path = $target_path.$format;
Will produce the following string:
/assets/img/notes(1).txt
Accept multiple dots in string.
$filename = 'company.jobtitle.field.text';
function formatDuplicateExtension($filename){
$stmt = NULL;
$format = explode('.', $filename);
$i = 0;
foreach($format as $key => $value){
if($value === end($format)){
$stmt .= '(1).'.$format[$i];
}elseif($key === count($format)-2){
$stmt .= $format[$i];
}else{
$stmt .= $format[$i].'.';
}
$i++;
}
return $stmt;
}
echo formatDuplicateExtension($filename);
$filename = 'company.jobtitle.field.text';
OUTPUTS: //-->/assets/imgages/company.jobtitle.field(1).text
$name = 'trees.vac2012.img.jpg';
OUTPUTS: //--> /assets/imgages/trees.vac2012.img(1).jpg
I've found a solution idk if it's the best one because regex searches and substitutions are involved a lot of times and it seems to be they're resources consuming functions.
//this function insert the $number in the name of the file before .extension
function InsertBeforeExtension($filename,$number){
$stmt = NULL;
$format = explode('.', $filename);
$i = 0;
foreach($format as $key => $value){
if($value === end($format)){
$stmt .= '('.$number.').'.$format[$i];
}elseif($key === count($format)-2){
$stmt .= $format[$i];
}else{
$stmt .= $format[$i].'.';
}
$i++;
}
return $stmt;
}
//this function check if there's a string like (number).ext in the name
//if yes increment the (number) in the string that become (number++).ext
//if no insert (1) before .ext
function insertnumber($string){
$matches=array();
$re = '/[(][0-9]+[)]\.[a-zA-Z]+/m';
preg_match_all($re, $string, $matches, PREG_SET_ORDER, 0);
if($matches[0][0]){
//if (number).ext is present
$re = '/[(][0-9]+[)]/m';
$str = $matches[0][0];
//select the (number) only
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
//remove parethesis
$str=substr($matches[0][0],1,-1);
//cast sting to an int for add a number
$int = (int)$str;
$int++;
//replace the last (number) match in the name of the file with (number++)
$re = '/(.*)[(][0-9]+[)]/m';
$subst = '${1}('.$int.')';
$result = preg_replace($re, $subst, $string);
}else{
//if (number).ext is not present insert (1) before .ext
$result=InsertBeforeExtension($string,1);
}
return $result;
};
$target_file = $target_path.$name;
//If the file exist repeat to find the number of file that doesn't exist
if( file_exists( $target_file )) {
while(file_exists( $target_file )){
$name=insertnumber($name);
$target_file = $target_path.$name;
}
}
The only problem is that if you have uploaded a file named like file(3).txt and you upload another file with the same name this function rename it in file(4).txt and not in file(3)(1).txt but for my scope this is not important
I've commented the code trying to be the most clear possible this solution seems to work well but i've not calculate the performance.

How to fix url contains arabic characters

I want to get the url of each file in certain directory
i tried string concatenation (like: domain.folder1.folder2.file.mp3) but some folders and files is with arabic characters that make error when using the url.
example:
this is my code output:
String A :
https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3
this code is not working in some android devices
but the next code works with all devices
String B:
https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3
Note: i got String B from internet download manager that converts it automatically when i tried to use string A
my question is:
how to convert String A to String B by php
and is there better way to readdir and get the url of each file
My code is:
if(is_dir($parent)){
if($dh = opendir($parent)){
while(($file = readdir($dh)) != false){
if($file == "." or $file == ".."){
//...
} else { //create object with two fields
sort($file);
$fileName = pathinfo($file)['filename'];
if(is_dir($parent."/".$file)){
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $path."/".$file, "directory"=> true);
} else {
$res = "https://linkimage2url.com".$path."/".$file;
$data[] = array('name'=> $fileName, 'subname'=> basename($path), 'url'=> $res , "directory"=> false);
}
Try this one, I've used once for a legacy project:
function encode_fullurl($url) {
$output = '';
$valid = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~!*\'();:#&=+$,/?#[]%';
$length = strlen($url);
for ($i = 0; $i < $length; $i++) {
$character = $url[$i];
$output .= (strpos($valid, $character) === false ? rawurlencode($character) : $character);
}
return $output;
}
$url ="https://linkimage2url.com/apps/quran full/محمد صديق المنشاوي/تسجيلات الإذاعة المصرية/009 - At-Taubah (The Repentance) سورة التوبة.mp3";
echo encode_fullurl($url);
output:
https://linkimage2url.com/apps/quran%20full/%D9%85%D8%AD%D9%85%D8%AF%20%D8%B5%D8%AF%D9%8A%D9%82%20%D8%A7%D9%84%D9%85%D9%86%D8%B4%D8%A7%D9%88%D9%8A/%D8%AA%D8%B3%D8%AC%D9%8A%D9%84%D8%A7%D8%AA%20%D8%A7%D9%84%D8%A5%D8%B0%D8%A7%D8%B9%D8%A9%20%D8%A7%D9%84%D9%85%D8%B5%D8%B1%D9%8A%D8%A9/009%20-%20At-Taubah%20(The%20Repentance)%20%D8%B3%D9%88%D8%B1%D8%A9%20%D8%A7%D9%84%D8%AA%D9%88%D8%A8%D8%A9.mp3
it is not very performing, but it should do what you need
this code worked for me
thanks every one
$res1 = "https://linkimage2url.com" .$path."/".$file;
$query = flash_encode ($res1);
$url = htmlentities($query);
function flash_encode($string)
{
$string = rawurlencode($string);
$string = str_replace("%2F", "/", $string);
$string = str_replace("%3A", ":", $string);
return $string;
}

PHP - Searching words in a .txt file

I have just learnt some basic skill for html and php and I hope someone could help me .
I had created a html file(a.html) with a form which allow students to input their name, student id, class, and class number .
Then, I created a php file(a.php) to saved the information from a.html into the info.txt file in the following format:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
and so on (The above part have been completed with no problem) .
After that I have created another html file(b.html), which require user to enter their name and id in the form.
For example, if the user input name2 and id2 in the form, then the php file(b.php) will print the result:
Class: classB
Class Number: 24
I have no idea on how to match both name and id at the same time in the txt file and return the result in b.php
example data:
name1,id1,classA,1
name2,id2,classB,24
name3,id3,classA,15
<?php
$name2 = $_POST['name2'];
$id2 = $_POST['id2'];
$data = file_get_contents('info.txt');
if($name2!='')
$konum = strpos($data, $name2);
elseif($id2!='')
$konum = strpos($data, $id2);
if($konum!==false){
$end = strpos($data, "\n", $konum);
$start = strrpos($data, "\n", (0-$end));
$row_string = substr($data, $start, ($end - $start));
$row = explode(",",$row_string);
echo 'Class : '.$row[2].'<br />';
echo 'Number : '.$row[3].'<br />';
}
?>
Iterate through lines until you find your match. Example:
<?php
$csv=<<<CSV
John,1,A
Jane,2,B
Joe,3,C
CSV;
$data = array_map('str_getcsv', explode("\n", $csv));
$get_name = function($number, $letter) use ($data) {
foreach($data as $row)
if($row[1] == $number && $row[2] == $letter)
return $row[0];
};
echo $get_name('3', 'C');
Output:
Joe
You could use some simple regex. For example:
<?php
$search_name = (isset($_POST['name'])) ? $_POST['name'] : exit('Name input required.');
$search_id = (isset($_POST['id'])) ? $_POST['id'] : exit('ID input required.');
// First we load the data of info.txt
$data = file_get_contents('info.txt');
// Then we create a array of lines
$lines = preg_split('#\\n#', $data);
// Now we can loop the lines
foreach($lines as $line){
// Now we split the line into parts using the , seperator
$line_parts = preg_split('#\,#', $line);
// $line_parts[0] contains the name, $line_parts[1] contains the id
if($line_parts[0] == $search_name && $line_parts[1] == $search_id){
echo 'Class: '.$line_parts[2].'<br>';
echo 'Class Number: '.$line_parts[3];
// No need to execute the script any further.
break;
}
}
You can run this. I think it is what you need. Also if you use post you can change get to post.
<?php
$name = $_GET['name'];
$id = $_GET['id'];
$students = fopen('info.txt', 'r');
echo "<pre>";
// read each line of the file one by one
while( $student = fgets($students) ) {
// split the file and create an array using the ',' delimiter
$student_attrs = explode(',',$student);
// first element of the array is the user name and second the id
if($student_attrs[0]==$name && $student_attrs[1]==$id){
$result = $student_attrs;
// stop the loop when it is found
break;
}
}
fclose($students);
echo "Class: ".$result[2]."\n";
echo "Class Number: ".$result[3]."\n";
echo "</pre>";
strpos can help you find a match in your file. This script assumes you used line feed characters to separate the lines in your text file, and that each name/id pairing is unique in the file.
if ($_POST) {
$str = $_POST["name"] . "," . $_POST["id"];
$file = file_get_contents("info.txt");
$data = explode("\n", $file);
$result = array();
$length = count($data);
$i = 0;
do {
$match = strpos($data[$i], $str, 0);
if ($match === 0) {
$result = explode(",", $data[$i]);
}
} while (!$result && (++$i < $length));
if ($result) {
print "Class: " . $result[2] . "<br />" . "Class Number: " . $result[3];
} else {
print "Not found";
}
}

how to save change from split content of text

I've managed to cut the string a sentence into a word. but the new results can be viewed in the browser when the program runs. but these results can not change the condition of the strings in the original text file. I want the contents of the original text file identical to compile the results in the browser. Well how ya how to store the results of the pieces of the word to the text file? in this case stored in notepad with a .txt extension.
To cut the text I use the following php code:
$width = strlen($openfile)/28000;
$wrapped = wordwrap($openfile, $width,'<br>');
//echo $wrapped;
$stringedit=str_replace(" ", "<br>", $openfile);
echo $stringedit;
result from browser is like this
You can use:
file_put_contents ( $fileName, $stringedit); //here filename indicates the name/path of source file.
the solution for it problem is like this ,it is 100% work:
<?php
$array_filename = glob('simpantoken/*.txt');
foreach ($array_filename as $fileteks)
{
$stringteks = file_get_contents($fileteks);
$konversi = strtolower($stringteks);
$jenistandabaca = array(',', '!', '?', '.', ':',';', '-');
$hapustandabaca = str_replace($jenistandabaca,'',$konversi);
$hapustandabaca = trim(preg_replace('/[^0-9a-z]+/i','', $konversi));
$hapustandabaca = preg_replace('/[^a-z\d]+/i', '', $konversi);
$hapustandabaca = preg_replace('/[^\w]+/','',$konversi);
$hapustandabaca = preg_replace('/\W+/','',$konversi);
$replacespasi = str_replace(" ", PHP_EOL, $konversi);
$konversistring = explode("/", $konversi);
$array = preg_split('/[\pZ\pC]+/u', $konversi);
$ubahkarakter = str_replace(" ", '<br/>', $konversi);
if(strpos($konversi,' ') > 0)
{
echo "ada spasi";
}
else
{
echo "tidak ada spasi";
}
$handle = fopen($fileteks, 'w');
fwrite($handle, $replacespasi);
fclose($handle);
}
?>

Categories