0

I wrote a function to insert some text into a txt file (using a foreach), but I'd like to go in a new line for each element. Any suggestiong?

This is my function:

function process_page($page) {
    $html = get_html($page);

    foreach($html->find("h1") as $div) {

        $show = $div;
        $show = strip_tags($show);

        $data = '\n' . $show;
        $ret = file_put_contents('mydata.txt', $data, FILE_APPEND | LOCK_EX);

        if($ret === false) {
            die('There was an error writing this file');
        }
        else {
            echo "$ret bytes written to file";
        }

    }
}

I tried to insert '\n' but it write it into text file

Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
James69
  • 229
  • 1
  • 6
  • 17

2 Answers2

1

Replace '\n' with "\n". The escape sequence is not recognized when you use '.

See the manual.

Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66
TarangP
  • 2,711
  • 5
  • 20
  • 41
1

To ensure that it's platform independant - use PHP_EOL, this ensures it's the right encoding for the platform your currently running on.

$data = PHP_EOL . $show;
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55