3

I've checked this and its not working for me ! PHP Write a variable to a txt file

So this is my code,please take a look ! I want to write all the content of the variable to the file. But when i run the code,its only write the last line of the content !

<?php
$re = '/<li><a href="(.*?)"/';
$str = '
<li><a href="http://www.example.org/1.html"</a></li>
                        <li><a href="http://www.example.org/2.html"</a></li>
                        <li><a href="http://www.example.org/3.html"</a></li> ';

preg_match_all($re, $str, $matches);
echo '<div id="pin" style="float:center"><textarea class="text" cols="110" rows="50">';
// Print the entire match result

foreach($matches[1] as $content)
  echo $content."\r\n";
$file = fopen("1.txt","w+");
echo fwrite($file,$content);
fclose($file);
?>

When i open 1.txt,its only show me

http://www.example.org/3.html

It's should be

http://www.example.org/1.html
http://www.example.org/2.html
http://www.example.org/3.html

Am i doing wrong anything?

Enuma
  • 61
  • 1
  • 10

2 Answers2

2

This

foreach($matches[1] as $content)
     echo $content."\r\n";

only iterates over the array and makes $content the last element (you have no {} so it is a one liner).

Simple demo of your issue, https://eval.in/806352.

You could use use implode though.

fwrite($file,implode("\n\r", $matches[1]));

You also could simplify this by using file_put_contents. Per the manual:

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

So you could just do:

$re = '/<li><a href="(.*?)"/';
$str = '
<li><a href="http://www.example.org/1.html"</a></li>
                        <li><a href="http://www.example.org/2.html"</a></li>
                        <li><a href="http://www.example.org/3.html"</a></li> ';

preg_match_all($re, $str, $matches);
echo '<div id="pin" style="float:center"><textarea class="text" cols="110" rows="50">';
file_put_contents("1.txt", implode("\n\r", $matches[1]));
chris85
  • 23,846
  • 7
  • 34
  • 51
0

Late answer but you can use file_put_contents with FILE_APPEND flag, also, don't use regex to parse HTML, use an HTML parser like DOMDocument, i.e.:

$html = '
<li><a href="http://www.example.org/1.html"</a></li>
<li><a href="http://www.example.org/2.html"</a></li>
<li><a href="http://www.example.org/3.html"</a></li>';

$dom = new DOMDocument();
@$dom->loadHTML($html); // @ suppress DOMDocument warnings
$xpath = new DOMXPath($dom);

foreach ($xpath->query('//li/a/@href') as $href) 
{
    file_put_contents("file.txt", "$href->nodeValue\n", FILE_APPEND);
}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268