I have an array something like below:
Array
(
[0] => IA62b066
[1] => IAca99de
[2] => IAafed13
[3] => IA49882c
[4] => IA5c9872
[5] => IA39b3e1
I want to export the only the value from this array to text file. Txt file should display data like this.
IA62b066
IAca99de
IAafed13
IA49882c
IA5c9872
IA39b3e1
I have tried many ways but I could not solve it.
file_put_contents("output/$fileName.txt", print_r($array, true));
Can anybody please help me solve it.
That will create test.txt file in the directory of php script with the content of the array.
<?php
$input = [
'IA62b066',
'IAca99de',
'IAafed13',
'IA49882c',
'IA5c9872',
'IA39b3e1'
];
$filePath = __DIR__ . DIRECTORY_SEPARATOR . 'test.txt';
$content = implode(PHP_EOL, $input);
file_put_contents($filePath, $content);
Try this:
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
foreach($your_array as $value){
fwrite($myfile, $value . '\n');
}
fclose($myfile);
?>
Related
I have an HTML form, like survey and have a PHP file with this code
<?php
$fieldA = $_POST["prezime"];
$fieldB = $_POST["ime"];
$fieldC = $_POST["datumrodjenja"];
$fieldD = $_POST["mestorodjenja"];
$fieldE = $_POST["rod"];
$fieldF = $_POST["prebivaliste"];
$fieldG = $_POST["brojpasosa"];
$fieldH = $_POST["izdatod"];
$fieldI = $_POST["vazido"];
$fieldJ = $_POST["profesija"];
$fieldK = $_POST["zanimanje"];
$fieldL = $_POST["fiksni"];
$fieldM = $_POST["mobilni"];
$fieldN = $_POST["email"];
$fieldO = $_POST["napomena"];
$keys = array($fieldA,$fieldB,$fieldC,$fieldD,$fieldE,$fieldF,$fieldG,$fieldH,$fieldI,$fieldJ,$fieldK,$fieldL,$fieldM,$fieldN,$fieldO); //THIS IS WHERE YOU PUT THE FORM ELEMENTS ex: array('$fieldA','$fieldB',etc)
$csv_line = $keys;
foreach( $keys as $key ){
array_push($csv_line,'' . $_GET[$key]);
}
$fname = 'prijave.csv'; //NAME OF THE FILE
$csv_line = implode(',',$csv_line);
if(!file_exists($fname)){$csv_line = $csv_line."\r\n" ;}
$fcon = fopen($fname,'a');
$fcontent = $csv_line;
fwrite($fcon,$csv_line);
fclose($fcon);
?>
The problem with this code is that it creates .csv file, but with no more than 2 rows. When 2 rows are filled with informations from the form, no more collecting.
And the second question, how to allow š ć đ č letters to be collected from the form via this script? Thank you!
I had a similar requirement for a project I was working on. I came up with this small function to write an array to a CSV file ( Comma Delimited ).
I used the fputcsv() function which is pretty handy.
The function accepts 2 arguments, the array name as well as the name you would like the CSV file to be called. Using the fopen, i open the an empty file in the directory where I want to save the CSV file.
I set the header if I need one and write that out to the file.
I then loop through the array and output each element and delimit it by a ",".
Once done, I close the file.
I understand this may not answer your full question, but I believe this will help you in someway.
If your array looks like the same format as the one below, Then the function I have provided will work.
Array
Array
(
[0] => John
[1] => Doe
[2] => England
[3] => Somewhere
[4] => Something
[5] => UK
[6] => Foo
[7] => Bar
[8] => Yes
[9] => Developer
[10] => Stack Overflow
[11] => No
[12] => 0123456778
[13] => johndoe#gmail.com
[14] => Smith
)
Function
<?php
//Change these strings back to what you need
$fieldA = "John";
$fieldB = "Doe";
$fieldC = "England";
$fieldD = "Somewhere";
$fieldE = "Something";
$fieldF = "UK";
$fieldG = "Foo";
$fieldH = "Bar";
$fieldI = "Yes";
$fieldJ = "Developer";
$fieldK = "Stack Overflow";
$fieldL = "No";
$fieldM = "0123456778";
$fieldN = "johndoe#gmail.com";
$fieldO = "Smith";
$array = array( $fieldA,$fieldB,$fieldC,$fieldD,$fieldE,$fieldF,$fieldG,$fieldH,$fieldI,$fieldJ,$fieldK,$fieldL,$fieldM,$fieldN,$fieldO );
//set the filename
$filename = "prijave";
//call the function and pass the above array and filename as arguments
array_to_csv( $array, $filename );
//function to write array to csv file using fputcsv()
function array_to_csv( $array, $filename ) {
//open the csv file
//set the path for the file - use a+ to set file pointer to end of file
$out = fopen( "/path/to/output/directory/".$filename.".csv" , 'a+' );
//header - optional, remove if not needed
$header = array( "Column 1 Name","Column 2 Name","Column 3 Name","Column 4 Name","Column 5 Name","Column 6 Name",
"Column 7 Name","Column 8 Name","Column 9 Name","Column 10 Name","Column 11 Name","Column 12 Name",
"Column 13 Name","Column 14 Name","Column 15 Name"
);
//write the header - optional, remove if not needed
fputcsv ( $out, $header, "," );
//foreach loop is if you have a multidimensional array- uncomment if it is
//foreach( $array as $line ) {
//write each line of the array to csv file
fputcsv( $out, $array, "," );
//}
//close the file
fclose( $out );
}
?>
I have tested the above code and it works as it should. I have a header that is written to the file, along with the values from the array beneath each column.
I have this sort of structure on a txt file.
[FILE_INFO]
[FIRST]
LOAD1= CPU
LOAD2 = RAM
[END_FIRST]
[GLOBAL_INDEX]
ELEC1=1235.12
GAZ2,1=1563.123
GAZ2,2= 28.56
[END_GLOBAL_INDEX]
[END_FILE_INFO]
What i need is to convert this txt structure to a php array , is this possible or txt structure is know ?
Array
(
[FILE_INFO] => Array
(
[FIRST] => Array
(
[LOAD1] => CPU
[LOAD2] => RAM
)
[GLOBAL_INDEX] => Array
(
[ELEC1] => 1235.12
[GAZ2] => Array
(
[1] => 1563.123
[2] => 28.56
)
)
)
)
Here is my approach:
$txt_file = file_get_contents("test.rt");
$rows = explode("\n", $txt_file);
$new_array = array(); $dimension = array();
foreach($rows as $row =>$data)
{
if($data[0] == "[" && substr($data, 0, 4) != "[END"){ // start
$output = str_replace( array('[',']') , '' , $data );
array_push($dimension, trim($output));
continue;
}else if(substr($data, 0, 4) == "[END"){ // end
$output = str_replace( array('[',']') , '' , $data );
array_pop($dimension);
continue;
}
$dim="";
foreach($dimension as $k=>$v){
$dim.= "['$v']";
}
$new_array.$dim[] = $data; // this is not working !!!!!
}
The problem is to position my cursor in the dimension of the array and insert the data
Try this:
<?php
$myfile = fopen("test.txt", "r");
// Iterate one line until end-of-file
while(!feof($myfile)) {
$text[] = fgets($myfile); // Add the data in an array
}
fclose($myfile);
print_r($text); // print the array
?>
I am new to PHP and working to get some results but failing to achieve my target. I have text file which contains data like this,
APAC|AU|enable|SYD1925|8|20150929|WORKING
APAC|AU|disable|ADL7235|3|20120123|RESIGNED
APAC|NZ|disable|NZ1356|6|20110123|RESIGNED
APAC|NZ|enable|NZ1356|3|20130123|WORKING
I am trying to search "AU" && "enable" for this text, line by line and I am a bit successful in it. Here is my Code example;
public function scan1()
{
$file = FCPATH.'uploads/example.txt';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
$search1 = "AU";
$search2 = "enable";
$lines = file($file);
foreach($lines as $line)
{
if(stristr($line,$search1) && stristr($line,$search2))
echo $line;
}
}
Now, I am trying to explode/split output data and assign variable / array to save in database but I am failing to do so, can someone please help or give me some direction to achieve this. Thank you
Please show us your_table scheme.
If '$db' is a handle of the db connection :
foreach($lines as $line)
{
if(stristr($line,$search1) && stristr($line,$search2))
{
$arr = explode("|", $line);
$query = "INSERT INTO your_table VALUES ('".$arr[0]."', '".$arr[1]."', '".$arr[2]."', '".$arr[3]."', '".$arr[4]."', '".$arr[5]."')";
$db->query($query);
}
}
First, obtain the file contents with file_get_contents:
$str = file_get_contents(FCPATH.'uploads/example.txt');
Then, use the regex (preg_match_all) to find all portion of text you're looking for:
preg_match_all("/APAC\\|(\w{2}\\|\w+)/", $str, $matches);
Then adapt the array so the 'AU' and 'enabled' are separated (array_map, explode):
$matches = array_map(function ($v) { return explode('|', $v); }, $matches[1]);
So, print_r($matches); returns:
Array
(
[0] => Array
(
[0] => AU
[1] => enable
)
[1] => Array
(
[0] => AU
[1] => disable
)
[2] => Array
(
[0] => NZ
[1] => disable
)
[3] => Array
(
[0] => NZ
[1] => enable
)
)
Finally, the foreach loop:
foreach($matches as $k => $kv)
{
$search1 = $kv[0]; // AU
$search2 = $kv[1]; // enabled
}
This works as expected:
public function scan1()
{
$file = FCPATH.'uploads/example.txt';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
$search1 = "AU";
$search2 = "enable";
$lines = file($file);
foreach($lines as $line)
{
if(strpos($line,$search1) !== false && strpos($line,$search2) !== false)
echo $line;
}
}
using strpos function for detection.
I have a file that has the following structure :
I'm trying to insert a new line at the end using this function :
ini_set('auto_detect_line_endings',true);//At the beginning of the php file
$handle = fopen("File.csv", "r+");
$line = array(
[0] => Trussville
[1] => L01
[2] => 8765
[3] => this is , a sample (xx)
);
fputcsv($handle, $line, ',', '"');
fclose($handle);
The result I get is as following :
Can help me please ?
Thanks
before writing, position the file pointer to the end of the file, like so:
...
fseek($handle, 0, SEEK_END);
fputcsv($handle, $line, ',', '"');
I am trying to pull the filename out of a directory without the extension.
I am kludging my way through with the following:
foreach ($allowed_files as $filename) {
$link_filename = substr(basename($filename), 4, strrpos(basename($filename), '.'));
$src_filename = substr($link_filename, 0, strrpos($link_filename) - 4);
echo $src_filename;
}
...But that can't work if the extension string length is more than 3.
I looked around in the PHP docs to no avail.
PHP has a handy pathinfo() function that does the legwork for you here:
foreach ($allowed_files as $filename) {
echo pathinfo($filename, PATHINFO_FILENAME);
}
Example:
$files = array(
'somefile.txt',
'anotherfile.pdf',
'/with/path/hello.properties',
);
foreach ($files as $file) {
$name = pathinfo($file, PATHINFO_FILENAME);
echo "$file => $name\n";
}
Output:
somefile.txt => somefile
anotherfile.pdf => anotherfile
/with/path/hello.properties => hello
try this
function file_extension($filename){
$x = explode('.', $filename);
$ext=end($x);
$filenameSansExt=str_replace('.'.$ext,"",$filename);
return array(
"filename"=>$filenameSansExt,
"extension"=>'.'.$ext,
"extension_undotted"=>$ext
);
}
usage:
$filenames=array("file1.php","file2.inc.php","file3..qwe.e-rt.jpg");
foreach($filenames as $filename){
print_r(file_extension($filename));
echo "\n------\n";
}
output
Array
(
[filename] => file1
[extension] => .php
[extension_undotted] => php
)
------
Array
(
[filename] => file2.inc
[extension] => .php
[extension_undotted] => php
)
------
Array
(
[filename] => file3..qwe.e-rt
[extension] => .jpg
[extension_undotted] => jpg
)
------
list($file) = explode('.', $filename);
Try this:
$noExt = preg_replace("/\\.[^.]*$/", "", $filename);
Edit in response to cletus's comment:
You could change it in one of a few ways:
$noExt = preg_replace("/\\.[^.]*$/", "", basename($filename));
// or
$noExt = preg_replace("/\\.[^.\\\\\\/]*$/", "", $filename);
Yes, PHP needs regex literals...