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
Related
I need to search a string in .cfg file, and delete the whole line. I'm using file_get_contents to retrieve the the data in .cfg file, and I'm storing it in a variable, searching is good but not knowing how to delete the whole line?
I have a string in following way:
user $username insecure-password $password
I want to search $username and delete the whole line.
Use a little Regex to match the line:
<?php
$file = 'blah
etc
user delboy1978uk insecure-password 123456
etc
etc';
$regex = '#\nuser\s\w+\sinsecure-password\s.+\n#';
preg_match($regex, $file, $matches);
$file = str_replace($matches[0], "\n", $file);
echo $file;
Which outputs:
blah
etc
etc
etc
See it here: https://3v4l.org/BcDWK
With this method you can read each config file line by line search in each line.
$h = fopen('yourfile', 'r') ;
$match = 'username' ;
$output = [] ;
if ($h) {
while (!feof($h)) {
$line = fgets($h);
//your current search function, which search each line
if ( your_search_function($line, $match) === false) {
//array $output will not contain matching lines.
$output[] = $line;
}
}
fclose($h);
//write back to file or do something else with $output
$hw = fopen('yourfile', 'w') ;
if( $hw ) {
foreach( $output as $line ) {
fputs($hw, $line) ;
}
fclose($hw) ;
}
}
I want to increment $userCount by 1 every time $data and $fileLineArr2[0] have the same value. Could someone explain why $userCount remains 0? I'm a programming student, so please keep help in a way that is understandable to someone with only intermediate experience.
if(!empty($_GET["user"]) && !empty($_GET["pass"]) && !empty($_GET["fname"]) && !empty($_GET["lname"])){
$handle = fopen($accountInfo, 'a') or die('Cannot open file: '.$accountInfo);
$data = $_GET["user"]."; ";
$data = strtoupper($data);
fwrite($handle, $data);
$data2 = $_GET["pass"]."; ";
fwrite($handle, $data2);
$data3 = $_GET["fname"]."; ";
fwrite($handle, $data3);
$data4 = $_GET["lname"].";\n";
fwrite($handle, $data4);
fclose($handle);
$reading2 = fopen($accountInfo, 'r') or die('Cannot open file: '.$accountInfo);
echo "$userCount";
while(!feof($reading2)){
$fileLines2 = fgets($reading2);
$fileLineArr2 = (explode("; ", $fileLines2));
//print_r($fileLineArr2);
**if($fileLineArr2[0] == $data)
{
$userCount++;
}**
echo "$fileLineArr2[0] ";
echo " $data". "\n";
echo "$userCount";
}
fclose($reading2);
if($userCount > 1)
{
$validSignUp = false;
?>
<font color='red'>Username already taken!</font>
<?php
}
elseif($userCount == 0)
{
;
}
else
{
$validLogin = true;
$validSignUp = true;
}
}
When reading from a file, there is an invisible new line character at the end of the string. You will want to remove that and then compare against the $data.
To remove the new line character, you can do something like
$string = trim(preg_replace('/\s+/', ' ', $string));
Where $string is the line from the file.
EDIT
Based on a discussion in the comments section, this is not what you want.
What you will want to do is the following:
$line = explode('; ', $lineData);
Where $lineData is the information being read from the file.
This will give you an array of all the elements that were listed on the line. We know that the username is listed in the first position, IE $line[0]. So we compare our data with that.
if ($line[0] == $data) {
$userCount++;
}
Where $data is the information we are comparing against.
I want write function something like this
getLine($mySteing){
.....
}
How to get line form file(file.txt) given sting include(matching)?. please help
define('COMPANY_FULL_NAME', 'sdfstd') = getLine( "define\(\'COMPANY_FULL_NAME\'\" );
file.txt
define ( 'APP_TITLE', 'Ekdi Inc' );
define('COMPANY_NAME', 'WosdfP');
define('COMPANY_FULL_NAME', 'sdfstd');
the following function will find all the lines that match your string, and it will echo the line number, as $i
function getLine($string)
{
$file = fopen("fle.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
$i = 0;
while(!feof($file))
{
$i++;
$line = fgets($file);
$pos = strpos($line, $string);
if( $pos !== false )echo $i.'<br/>';
}
fclose($file);
}
by the way, don't escape characters, don't use \ within the string parameter, as you did in yur code
read http://php.net/manual/en/function.strpos.php
Lets say the text file " data1.txt" contains:
56715||Jim||Green||19
5678||Sara||Red||92
53676||Mark||Orange||6
56787||Mike||Purple||123
56479||Sammy||Yellow||645
56580||Martha||Blue||952
ect...
.
.
I would like to echo only the line beginning with "5678||". "5678" is the exact $refVal or reference value. The line should display like this:
My name is: $nameVar
My color is: $colorVar
My number is: $numVar
Thanks...
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgetcsv($fh, 0, '||')) {
if ($line[0] == 5678) {
echo <<<EOL
My name is: $line[1]
My color is $line[2]
My number is $line[3]
EOL;
break; // if there's only ever one '5678' line in the, get out now.
}
}
fclose($fh);
alternate version, as suggested by Jared below. Probably will be faster, as it only does the array creation on the line that actually matches, and not for each line as the fgetcsv version does.
$fh = fopen('data1.txt', 'r') or die('Unable to open data1.txt');
while($line = fgets($fh)) {
if (strpos($line, '5678||') === 0) { // only if right at start of string
$data = explode('||', $line);
echo <<<EOL
my name is blah blah blah
EOL;
break;
}
}
You can split each line into an array using explode, like so:
foreach ($lines as $line)
{
$t = explode('||', $line);
if ($t[0] == $refVal) {
// echo the rest of $t array however you want
// $t[1] would be the name, $t[2] the color, etc
}
}
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