How to append newline to variable?

Discussion in 'PHP' started by postcd, Oct 15, 2014.

  1. #1
    Please how to achieve that emails are added to the file one per line, not appending all on one line?

    my current code:
    // input one email
    email = $_POST['email'];
    $stuff = serialize($email);
    $handle = fopen('email_list.txt','w+');
    fwrite($handle, $stuff);
    
    // print all emails
    $contents = unserialize(file_get_contents('email_list.txt'));
    echo $file_contents;
    PHP:
    i tried like:
    fwrite($handle, $stuff . "\n");
    or
    $stuff = serialize($email) . "\n\r";

    but none works :(
     
    postcd, Oct 15, 2014 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,893
    Likes Received:
    4,553
    Best Answers:
    123
    Trophy Points:
    665
    #2
    I'm not sure what benefit there is in serialising in the text document but this is what I'd do.

    // input one email
    $email = myValidateEmailFunction($_POST['email']);
    if ($email){
       $handle = fopen('email_list.txt','w+');
       fwrite($handle, $email . "\n");
    }
    // print all emails
    $contents = file_get_contents('email_list.txt');
    echo nl2br($file_contents);
    PHP:
    If you need to serialise then you need to unserialise on a line by line basis.
     
    sarahk, Oct 15, 2014 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    You can simply do it like this:
    
    // input one email
    $email = (isset($_POST['email']) ? $_POST['email'].PHP_EOL : '');
    
    $handle = fopen('email_list.txt','a');
    fwrite($handle,$email);
    
    // print all emails
    foreach (file('email_list.txt') as $key => $value) {
       echo $value.'<br>';
    }
    
    PHP:
     
    PoPSiCLe, Oct 15, 2014 IP
    postcd likes this.