-1

i'm trying to run file_put_contents instead of echo but I can not solve it. This is my code:

$DOM = new DOMDocument();
$DOM->loadHTML($html);
$a = $DOM->getElementsByTagName('a');
foreach($a as $link){
    echo $link->getAttribute('href').'<br />';

I tried to update echo $link->getAttribute('href').'<br />'; with file_put_contents("$project.txt", $link->getAttribute('href').'<br />'); but instead of getting something like this:

http://domain1.com/url-page-1/
http://domain2.com/url-page-2/
http://domain3.com/url-page-3
(...)

I got just this:

http://domain1.com/url-page-1/<br />

Any ideas?

Mike Nowak
  • 125
  • 1
  • 1
  • 4
  • 1
    [`, FILE_APPEND`](http://www.php.net/file_put_contents) – Wrikken Oct 17 '13 at 18:51
  • The basic reason for that your code it's not working is because you rewrite your file `$project.txt` with every loop. As @Amal Murali well said the you should give the third parameter to `file_put_contents`, `FILE_APPEND`, for the file to not be rewritten. – Cristian Bitoi Oct 17 '13 at 18:57

1 Answers1

0

Use PHP_EOL instead:

file_put_contents("$project.txt", $link->getAttribute('href').PHP_EOL);

If you want to append to the file, then use the FILE_APPEND flag:

$text = $link->getAttribute('href').PHP_EOL;
file_put_contents("$project.txt", $text , FILE_APPEND);

Your foreach loop would look like this:

foreach($a as $link){
    echo $link->getAttribute('href').'<br />';
    $text = $link->getAttribute('href').PHP_EOL;
    file_put_contents("$project.txt", $text , FILE_APPEND);
}
Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150