Remove blank from text file - php

I want to remove blank line from this text file :
test1
test2
test3
test4
So I try this code in PHP :
$file = __DIR__.$namefile;
foreach ($file as $k => $v) {
if (!trim($v))
unset($lines[$k]);
}
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
$array1[] = $nl;
}
But it does not work. Thanks for your help !

How about exploding each new line and checking if it's empty?
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array();
foreach ($lines AS $line) {
if (!empty($line)) {
$result[] = $line;
}
}
$result = implode("\n", $result);
Or, as Henders suggests, look at https://stackoverflow.com/a/7972266/1441858:
<?php
$content = fopen($file = __DIR__.$namefile, "r");
$lines = explode("\n", $content);
$result = array_filter($lines, 'trim');
$result = implode("\n", $result);

$file = __DIR__.$namefile;
$f = fopen($file, "r");
$array1 = array();
//Extract all url from file
while ( $line = fgets($f, 1000) ) {
$nl = mb_strtolower($line,'UTF-8');
if (trim($line) != "") {
$array1[] = $nl;
}
}
fclose($f);

$file = __DIR__.$namefile;
$lines = explode("\n", file_get_contents($file));
$result = array_filter($lines);
echo implode("\n", $result);
file_put_contents($file, implode("\n", $result)); //save
Or use:
$result = array_filter($lines, 'trim');
If there can be whitespaces in blank lines.

Related

How to split a php array into several parts to insert them in csv column names?

I wrote a code that allows me to read an excel file, transform it into csv and make modifications on it. I add at the end of this file 10 columns, the problem is that the name of the columns is added at once with "PICT1;PICT2; PICT3;PICT4;..." in only one column at the end of the 10. I would like each column to be called PICT1, PICT2, PICT3... How do I do this?
Currently I have this:
I would like that:
<?php
function multiSplit($string)
{
$output = array();
$cols = explode(",", $string);
foreach ($cols as $col)
{
$dashcols = explode("-", $col);
$output[] = $dashcols[0];
}
return $output;
}
//Modifications on csv file
$delimiter = $delimiterpost;
$csv_data = array();
$row = 1;
if (($handle = fopen($nomcsv, 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
//Add columns at the end
$data['Pictures Names'] = (!empty($data[4]) ? ($data[7] ?: '') . "_" . $data[4] . '.jpg' : '');
$data['Color-Description'] = (!empty($data[3]) ? (ltrim($data[4], '0') ?: '') . "-" . $data[3] : '');
$out = multiSplit($data[23]);
$data['PICT1'] = $out[0];
$data['PICT2'] = $out[1];
$data['PICT3'] = $out[2];
$data['PICT4'] = $out[3];
$data['PICT5'] = $out[4];
$data['PICT6'] = $out[5];
$data['PICT7'] = $out[6];
$data['PICT8'] = $out[7];
$data['PICT9'] = $out[8];
$data['PICT10'] = $out[9];
// Delete three columns
unset($data[1]);
unset($data[2]);
unset($data[3]);
//Modifications on the fourth line
if ($row == 4)
{
//All uppercase
$data = array_map('strtoupper', $data);
$data = str_replace(' *', '', $data);
$data = str_replace('/', '', $data);
//Replacement of spaces by an underscore
$data = str_replace(' ', '_', $data);
$data = str_replace('__', '_', $data);
//Replacement name by another name
$data = str_replace('STYLE_COLOR.JPG', 'PICT', $data);
$data = str_replace('COLOR-DESCRIPTION', 'COLOR_DESCRIPTION', $data);
array_filter($data, function($value) { return !is_null($value) && $value !== ''; });
for ( $i=1; $i<=10; $i++ ){
$data[] = "PICT$i";
}
}
if ($data[22])
{
$data = str_replace(',', 'ยง- ', $data);
}
$csv_data[] = $data;
$row++;
}
fclose($handle);
}
$csv_data = array_slice($csv_data, 3); // this will remove first three elements
array_pop($csv_data);// this will remove last element from array
if (($handle = fopen($nomcsv, 'w')) !== FALSE) {
foreach ($csv_data as $data) {
fputcsv($handle, $data, $delimiter);
}
fclose($handle);
}
Replace
$data[] ='PICT1'.$delimiter.'PICT2'.$delimiter.'PICT3'.$delimiter.'PICT4'.$delimiter.'PICT5'.$delimiter.'PICT6'.$delimiter.'PICT7'.$delimiter.'PICT8'.$delimiter.'PICT9'.$delimiter.'PICT10';
With a loop that creates the additional array items
// clean out any empty titles as there appear to be some at the end of the array
array_filter($data, function($value) { return !is_null($value) && $value !== ''; });
for ( $i=1; $i<=10; $i++ ){
$data[] = "PICT$i";
}

explode text file into array depend on comma

I'd like to convert my text.tx into array depend on only comma for example:
if I have this text:
so what I need to execute my array like that:
please check my code, my code not work well because it's depend on comma and newline:
<?php
$lines = file ("text.txt");
foreach($lines as $line) {
$data[] = explode(',', $line);
}
?>
<pre>
<?php
print_r($data);
?>
</pre>
$handle = fopen("text.txt", "r");
if ($handle) {
$data = [];
while (($line = fgets($handle)) !== false) {
$data[] = explode(',', $line);
}
fclose($handle);
echo "<pre>";
print_r($data);
} else {
// error opening the file.
}

PHP fwrite() , could not fill txt

after code execute my file look like this:
1.info
2.
3.info
4.
5.info
....
I tried with different mode in fopen but still the same.
<?php
$file = 'data.txt';
$lines = file($file);
$newArr = array();
$f = fopen($file,'r+');
foreach($lines as $value){
$newArr[] = $value;
}
unset($newArr[$_GET['id']-1]);
foreach($newArr as $vv){
fwrite($f, $vv.PHP_EOL);
}
fclose($f);
?>
It appears that this is the same and should work:
$file = 'data.txt';
$lines = file($file, FILE_SKIP_EMPTY_LINES);
unset($lines[$_GET['id']-1]);
file_put_contents($file, $lines);
For whatever reason using fwrite():
$file = 'data.txt';
$lines = file($file, FILE_SKIP_EMPTY_LINES);
unset($lines[$_GET['id']-1]);
$f = fopen($file, 'w');
fwrite($f, implode($lines));
/*
foreach($lines as $vv) {
fwrite($f, $vv);
}
*/

How to Format CSV to ARRAY?

Can someone show me how to easily format an array with values like this?
I have a CSV file with values like below:
27383,15.99
80448,19.99
132876,11.99
150438,120
This is the format I would like:
$array[0]['id'] = 27838
$array[0]['price'] = 15.99
$array[1]['id'] = 80448
$array[2]['price'] = 19.99
What I have now is:
$data = file_get_contents('id_and_price.csv');
$data = explode(',', $data);
print_r($data);
//foreach($data as $d) {
// echo $d;
//}
You can do this quite easily with fgetcsv():
$arr = array();
$header = array('id', 'price');
$file = fopen('id_and_price.csv', 'r');
while($item = fgetcsv($file))
{
$arr[] = array_combine($header, $item);
}
print_r($arr);
<?php
$f = fopen('filename', 'r');
$arr = array();
while ($l = fgetcsv($f)) {
$arr[] = array_combine(array('id', 'price'), $l);
}
var_dump($arr);
?>
you need to use php explode...
http://php.net/manual/en/function.explode.php
$csv = "piece1,piece2,piece3,piece4,piece5,piece6";
$array = explode(",", $csv);
echo $array[0]; // piece1
echo $array[1]; // piece2

read a text file with PHP and display all text after a certain string

I have a text file with lots of text, and I want to display a part of it on the screen with PHP.
At a certain point there's string like ITEM DESCRIPTION:
What I want to get all content from this string (just after it) to the end of the file.
This is my code so far:
$file = "file.txt";
$f = fopen($file, "r");
while ($line = fgets($f, 1000))
echo $line;
:)
How about you use strstr() and file_get_contents() ?
$contents = strstr(file_get_contents('file.txt'), 'ITEM DESCRIPTION:');
# or if you don't want that string itself included:
$s = "ITEM DESCRIPTION:"; # think of newlines as well "\n", "\r\n", .. or just use trim()
$contents = substr(strstr(file_get_contents('file.txt'), $s), strlen($s));
$file = "file.txt";
$f = fopen($file, 'rb');
$found = false;
while ($line = fgets($f, 1000)) {
if ($found) {
echo $line;
continue;
}
if (strpos($line, "ITEM DESCRIPTION:") !== FALSE) {
$found = true;
}
}
What about
$file = "file.txt";
$f = fopen($file, "r");
$start = false;
while ($line = fgets($f, 1000)) {
if ($start) echo $line;
if ($line == 'ITEM DESCRIPTION') $start = true;
}
?

Categories