PHP fopen-将变量写入txt文件

PHP fopen-将变量写入txt文件,php,fopen,Php,Fopen,我已经检查过了,它对我不起作用! 这是我的代码,请看一看!我想将变量的所有内容写入文件。但当我运行代码时,它只写最后一行内容 <?php $re = '/<li><a href="(.*?)"/'; $str = ' <li><a href="http://www.example.org/1.html"</a></li> <li><a href="http://w

我已经检查过了,它对我不起作用!

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

<?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);
?>
我做错什么了吗?

这个

foreach($matches[1] as $content)
     echo $content."\r\n";
仅在数组上迭代,并使
$content
成为最后一个元素(您没有
{}
,因此它是一个单行程序)

您的问题的简单演示

不过你可以用

您还可以通过使用来简化此过程。根据手册:

此函数与依次调用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]));

$re='/
  • 延迟回答,但您可以使用with
    FILE\u APPEND
    标志,另外,不要使用正则表达式解析
    HTML
    ,请使用
    HTML
    解析器,例如:

    $html='1!'
    
  • 太好了,时间一过,请接受答案。另请查看更新。感谢您的帮助;)
    fwrite($file,implode("\n\r", $matches[1]));
    
    $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]));
    
    $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);
    }