PHP fopen - 将变量写入txt文件

3

我已经检查过了,但是对我没有用!PHP将变量写入txt文件

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

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

我有什么做错的吗?

2个回答

2
这是一个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来简化操作。根据手册:

这个函数与连续调用 fopen()、fwrite() 和 fclose() 函数写入文件的过程完全一致。

因此您可以直接这样做:
$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

0
晚回答了,但你可以使用 file_put_contentsFILE_APPEND 标志,同时不要使用正则表达式来解析 HTML,而是使用像 DOMDocument 这样的 HTML 解析器,例如:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接