omgpwned
omgpwned

Reputation: 147

Newline In File

I got this problem... I have a php script named getdata.php

 <?php

    $filename = "data";
    $data = file_get_contents($filename);
    $data = explode("\n", $data);

    print_r($data);
?>

And a data file

name admin\nname guest

When I run the php code I just get:

Array ( [0] => name admin\nname guest ) 

I want the output is

Array ( [0] => name admin [1] => name guest ) 

What should I do?

Upvotes: 1

Views: 78

Answers (3)

Ali Almoullim
Ali Almoullim

Reputation: 1038

why not trying to use <br> instead

<?php

    $filename = "data";
    $data = file_get_contents($filename);
    $data = explode("<br>", $data);

    print_r($data);
?>

Upvotes: 0

Rajeev Bera
Rajeev Bera

Reputation: 2019

Based on the comments please find my Updated

Try with '\n\n'

<?php

    $filename = "data";
    $data = file_get_contents($filename);
    $pieces = explode('\n\n', $data);

    echo $pieces[0]; // name admin
    echo $pieces[1]; // name guest
?>

Upvotes: -1

Samveen
Samveen

Reputation: 3540

Change this

    $data = explode("\n", $data);

to

    $data = explode("\\n", $data);

The issue is that in the data file \n is a string of 2 characters \ and n, but in your explode invocation it is a single control character \n. By changing this to \\n it's now the same 2 characters as the data

Upvotes: 2

Related Questions