PHP: how to remove the last line break from a text file?

In my school work, I built a website for a fictional space museum in my city using PHP. It has data and data embedding systems, but I have a consultation problem that I want to know how to solve: how to remove the last line break from a file?

Data inclusion

In a limited area of ​​the site, I have an HTML5 form with 5 fields (name, address, phone number, sex, and visited exhibitions) that sends data using a POST function to PHP, which writes it to a given txt file using the command fwrite

:

fwrite ($pointer, "$name | $addres | $telephone | $sex | $exhibitions " .PHP_EOL);

      

As you can see, it writes to the txt file the data entered in the form plus a line break. A pointer is a variable used fopen

to open the file I need to work. Output example:

Márcio Aguiar | Belmiro Braga | 1234-5678 | M | The planets of the solar system
Joana Tobias | Santos Dummont Avenue | 8765-4321 | F | Black holes, satellites

Data consultation

Then there is the consultation system. It has a loop that runs until the file finishes Inside this loop, there is a named variable $buffer

that gets one line of the txt file each time. Then explode

d is an array named $lines[$counter]

. To print it out nicely, I use array_combine

where I join the field names in another array ( $keys

) to the values ​​written in $lines[$counter]

and assign that to the value $combined[$counter]

. The loop then ends, and I use print_r

internally <pre></pre>

to see the data written to $combined

, while mantaining spaces and breaks that would otherwise ignore HTML. Here is the code:

$keys = array ("Name", "Address", "Telephone", "Sex", "Visited exhibition");
for ($counter=0;!feof($reader);$counter++){
    $buffer = fgets($reader);
    $lines[$counter] = explode(" | ", $buffer);
    $combined[$counter] = array_combine($keys, $lines[$counter]);
}
echo "<pre>";
print_r($combined);
echo "</pre>";

      

Output example:

    Array
    (
    [0] => Array
        (
            [Name] => Márcio Aguiar
            [Address] => Belmiro Braga Street
            [Telephone] => 1234-5678
            [Sex] => M
            [Visited exhibitions] => Planets of Solar System 

        )

    [1] => Array
        (
            [Name] => Joana Tobias
            [Address] => Santos Dummont Avenue
            [Telephone] => 8765-4321
            [Sex] => F
            [Visited exhibitions] => Black Holes, Satellites 

        )

    [2] => 
    )

      

Here you can see that the array 2

was created empty. This is caused by the last line containing only the line break inserted in the form above. I need to remove this last line break, and only that one, but dont know how. I want to know! Ignorance causes an error to be shown when execution comes in array_combine

, as it requires the two arrays to have the same number of elements and are 2

empty. Here's the error:

Warning: array_combine (): Both parameters must have equal cardinality in E: \ Aluno \ Documents \ Wamp \ www \ trab_1 \ area_restrita \ consulta.php on line 60

+3


source to share


2 answers


Original answer:

To remove a trailing line break from any text you can use trim () , however in your case you just need to use fopen

in add mode
:

$handle = fopen("/path/to/file", "a");

      

Then get rid of PHP_EOL

:

fwrite ($pointer, "$name | $addres | $telephone | $sex | $exhibitions");

      




Edit: You are correct that the append is not being added to the new line. I was wrong. Therefore, you can use trim () as I mentioned earlier. I created a quick example using file_get_contents()

and file_put_contents()

and it seems to do what you want:

<?php

$file = 'test.txt';

// Set existing contents (for testing sake)
$orig_contents = "bob | 123 fake street | 1234567890 | yes, please | no\n";
$orig_contents .= "bob | 123 fake street | 1234567890 | yes, please | no\n";
$orig_contents .= "bob | 123 fake street | 1234567890 | yes, please | no\n";
$orig_contents .= "bob | 123 fake street | 1234567890 | yes, please | no\n";
file_put_contents($file, $orig_contents);

// Here is how you could add a single new line with append mode
// Notice the trailing \n
file_put_contents($file, "billy | 456 fake street | 2345678901 | no | yes\n", FILE_APPEND);

// Get contents from the file and remove any trailing line breaks
$contents = trim(file_get_contents($file));

$keys = array ("Name", "Address", "Telephone", "Sex", "Visited exhibition");

// Explode based on the new line character
$lines = explode("\n", $contents);

foreach ($lines as $line) {
    $values = explode(" | ", $line);
    $combined[] = array_combine($keys, $values);
}

print_r($combined);

      

Prints:

Array
(
    [0] => Array
        (
            [Name] => bob
            [Address] => 123 fake street
            [Telephone] => 1234567890
            [Sex] => yes, please
            [Visited exhibition] => no
        )

    [1] => Array
        (
            [Name] => bob
            [Address] => 123 fake street
            [Telephone] => 1234567890
            [Sex] => yes, please
            [Visited exhibition] => no
        )

    [2] => Array
        (
            [Name] => bob
            [Address] => 123 fake street
            [Telephone] => 1234567890
            [Sex] => yes, please
            [Visited exhibition] => no
        )

    [3] => Array
        (
            [Name] => bob
            [Address] => 123 fake street
            [Telephone] => 1234567890
            [Sex] => yes, please
            [Visited exhibition] => no
        )

    [4] => Array
        (
            [Name] => billy
            [Address] => 456 fake street
            [Telephone] => 2345678901
            [Sex] => no
            [Visited exhibition] => yes
        )

)

      

+3


source


The problem is in the way you read the file. You are checking EOF before reading from a file. But feof()

will be invalid until you try to read while you are at the end of the file.

Instead, you should check if a fgets()

string is returning .

for ($counter = 0; $buffer = fgets($reader); $counter++) {
    $lines[$counter] = explode(" | ", $buffer);
    $combined[$counter] = array_combine($keys, $lines[$counter]);
}

      

DEMO



To explain further, let's assume you have a file with one line in it. When $counter

there is 0

, you call feof()

and it returns false

. So you read the first line and add it to $lines

and $combined

. Then you increment $counter

and return to the beginning of the loop.

When $counter

there is 1

, you call feof()

. This is still not the case, because you haven't tried reading at the end of the file yet. Then you try to read the next line, but there is no line there, fgets

returns false

and you assign it $buffer

. This is treated as an empty string explode()

, so you add an empty array to $lines

and $combined

. Then you increment $counter

and return to the beginning of the loop.

Then you call feof()

, and this time it returns true

because you tried to read at the end of the file in the previous iteration. Thus, the contour ends.

As you can see from the above, although the file only has 1 line, you are getting 2 entries in your arrays because you haven't tested EOF until you read too far.

0


source







All Articles