PHP fopen - 将变量写入 txt 文件

PHP fopen - Write a variable to a txt file

我已经检查过了,它对我不起作用! PHP Write a variable to a txt file

这是我的代码,请看一下!我想将变量的所有内容写入文件。但是当我 运行 代码时,它只写最后一行内容!

<?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);
?>

当我打开 1.txt 时,它只显示我

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

应该是

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

我做错了什么吗?

这个

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

只遍历数组并使 $content 成为最后一个元素(你没有 {} 所以它是一个单行)。

您的问题的简单演示,https://eval.in/806352

不过您可以使用 implode

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

您也可以使用 file_put_contents 来简化它。根据手册:

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

所以你可以这样做:

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

迟到的答案,但您可以使用 file_put_contents with FILE_APPEND flag, also, don't use regex to parse HTML, use an HTML parser like DOMDocument,即:

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