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);
}
?>
Related
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
I want for example to scan this $lang['foo1']='foo2'; from a PHP file so I tried
this but it doesn't work.
$file = "../lang/lang.en.php";
if(file_exists($file)) {
$text = fopen($file, 'r+');
$content = trim(file_get_contents($file, NULL, NULL, 221));
$i = 0;
do {
$n = sscanf($content, "\$lang['%s']=%s;", $s1[$i], $s2[$i]);
echo $s1[$i].'==>'.$s2[$i];
$i++;
} while($s1[$i]! = '' && $s2[$i] != '');
}
What is my problem?
You should just include('../lang/lang.en.php') like a normal PHP file.
Also, it's possible to make lang.en.php return an array directly with return, http://nl3.php.net/manual/en/function.return.php
I would recommend to use preg_match_all() in your case.
// Match
// $lang['PAGE_TITLE']='Meine Webseite Titel';
$content = file_get_contents('../lang/lang.en.php');
preg_match_all("~\$lang\['.+'\]\s=\s'.+';~", $content, $result);
var_dump($result);
i am uploading the image into the server , need to place the _ in place of gap in the image. Like if the name of image is Stack Flow.jpg, i need to send it as Stack_Flow.jpg in the directory as well in the email. HOw could be possible with the following code. i have tried but no success.. I am sending the 4 files in one form, code as ---
$filea = $_FILES['FILE1']['name'];
$fileb = $_FILES['FILE2']['name'];
$filec = $_FILES['FILE3']['name'];
$filed = $_FILES['FILE4']['name'];
$order_image_a='order_'.$orderId.'_'.$filea;
if(!empty($filea)) move_uploaded_file($_FILES['FILE1']['tmp_name'], "../files/$order_image_a");
$order_image_b='order_'.$orderId.'_'.$fileb;
if(!empty($fileb)) move_uploaded_file($_FILES['FILE2']['tmp_name'], "../files/$order_image_b");
$order_image_c='order_'.$orderId.'_'.$filec;
if(!empty($filec)) move_uploaded_file($_FILES['FILE3']['tmp_name'], "../files/$order_image_c");
$order_image_d='order_'.$orderId.'_'.$filed;
if(!empty($filed)) move_uploaded_file($_FILES['FILE4']['tmp_name'], "../files/$order_image_d");
i am using below function, how could i apply it for all four files--
<script>
function convertSpecialChars($str) {
$str = str_replace( " ", "_", $str );
return $str;
}
</script>
here is a quick example in php:
<?php
$name = "Stack Flow.jpg";
echo preg_replace('/[\s\-]+/', '_', $name );
?>
returns Stack_Flow.jpg
http://codepad.org/MQoEZ2wv
This is not a script but PHP..
<?
function convertSpecialChars($str) {
$str = str_replace( " ", "_", $str );
return $str;
?>
//do the same for all other images..
$filea = str_replace(' ', '_', $filea;
$order_image_a='order_'.$orderId.'_'.$filea;
if(!empty($filea)) move_uploaded_file($_FILES['FILE1']['tmp_name'], "../files/$order_image_a");
Using:
<?php
function convertSpecialChars($str) {
$str = str_replace( " ", "_", $str );
return $str;
}
?>
And then your code:
$filea = $_FILES['FILE1']['name'];
$fileb = $_FILES['FILE2']['name'];
$filec = $_FILES['FILE3']['name'];
$filed = $_FILES['FILE4']['name'];
$order_image_a='order_'.$orderId.'_'.convertSpecialChars($filea);
if(!empty($filea))
move_uploaded_file($_FILES['FILE1']['tmp_name'], "../files/$order_image_a");
$order_image_b='order_'.$orderId.'_'.convertSpecialChars($fileb);
if(!empty($fileb))
move_uploaded_file($_FILES['FILE2']['tmp_name'], "../files/$order_image_b");
$order_image_c='order_'.$orderId.'_'.convertSpecialChars($filec);
if(!empty($filec))
move_uploaded_file($_FILES['FILE3']['tmp_name'], "../files/$order_image_c");
$order_image_d='order_'.$orderId.'_'.convertSpecialChars($filed);
if(!empty($filed))
move_uploaded_file($_FILES['FILE4']['tmp_name'], "../files/$order_image_d");
Or if possible, you could do it in a loop (less duplicate code):
for ($i = 1; $i <= 4; $i++)
{
$file = $_FILES['FILE' . $i]['name'];
$order_image = 'order_' . $orderId . '_' . convertSpecialChars($file);
if(!empty($file))
move_uploaded_file($_FILES['FILE' . $i]['tmp_name'], "../files/$order_image");
}
In your code change $order_image_a='order_'.$orderId.'_'.$filea; and other similar lines to
$order_image_a='order_'.$orderId.'_'.convertSpecialChars($filea);
But will better if you will know how work your code.
I have a csv file with this:
software
hardware
educational
games
languages
.
.
.
I need a new csv file with:
software;hardware;educational;games;languages;....
How can I do that?
I'm doing:
<?php
$one = file_get_contents('one.csv');
$patterns =" /\\n/";
$replacements = ";";
$newone = preg_replace($patterns, $replacements, $one);
echo $newone;
file_put_contents('newone.csv', $newone );
?>
This adds the semicolon at the end of the line but the line break is still there
Surprisingly none of you mentioned file() that returns what he needs:
$cont = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
file_put_contents('somefile.csv',implode(';',$cont));
2 lines of code without using slow regex
OR
if you need less code, here with 1 line of code, the way i like !
file_put_contents(
'somefile.csv',
implode(
';',
file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
)
);
Here is how you can do this.
Edit : tested this, works correct.
<?php
$row = 1;
$readHandle = fopen("in.csv", "r"); // open the csv file
$writeHandle = fopen("out.csv","w");
$subArr = array();
while (($data = fgetcsv($readHandle, 1000, "\n")) !== FALSE) {
$myStr = $data[0]; // this stores the zeroth column of each CSV row
$subArr[] = $myStr; // subArr contains all your words
}
fputcsv($writeHandle,$subArr,";"); // it creates a CSV with single line seperated by ;
fclose($readHandle);
fclose($writeHandle);
?>
I guess you could get a preg_match_all() to get every alphanumeric word surrounded by quotes into an array.
Then you just loop on that array and display them adding a semicolon.
as a one off, I would run home to mama...
perl -p -i -e 's|(.*)\n|$1;|m' one.cvs
Your file may have carriage returns. Try this:
$newone = str_replace("\r\n", ';', $one);
To cover all possibilities:
<?php
$file = 'data.csv';
file_put_contents($file, '"software"
"hardware"
"educational"
"games"
"languages"
');
$input_lines = file($file);
$output_columns = array();
foreach($input_lines as $line){
$line = trim($line); // Remove trailing new line
$line = substr($line, 1); // Remove leading quote
$line = substr($line, 0, -1); // Remove trailing quote
$output_columns[] = $line;
}
echo implode(';', $output_columns);
Beware: this code assumes no errors in input file. Always add some validation.
I suggest doing it like this:
<?php
$one = file_get_contents('one.csv');
$patterns ="/\\r?\\n/";
$replacements = ";";
$newone = preg_replace($patterns, $replacements, $one);
echo $newone;
file_put_contents('newone.csv', $newone );
?
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