PHP fopen - writing variable to txt file

I tested this and didn't work for me! PHP Writing variable to txt file

So this is my code, please take a look! I want to write all the contents of a variable to a file. But when I run the code, it only writes the last line of 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 it only shows

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

It should be

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

      

Am I doing something wrong?

+3


source to share


2 answers


it

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

      

only iterates over the array and makes it the $content

last element (you don't {}

, so this is one liner).

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

You can use implode

it though.



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

      

You can also simplify this by using file_put_contents

. In the manual:

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

So, you can simply 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]));

      

+2


source


Late answer, but you can use file_put_contents with a flag FILE_APPEND

, also don't use regex for parsing HTML

, use a HTML

parser like DOMDocument , that is:



$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);
}

      

0


source







All Articles