【问题标题】:PHP fopen - Write a variable to a txt filePHP fopen - 将变量写入 txt 文件
【发布时间】:2017-05-27 13:58:48
【问题描述】:

我已经检查过了,它对我不起作用! 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

我做错什么了吗?

【问题讨论】:

    标签: php fopen


    【解决方案1】:

    这个

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

    【讨论】:

    • 很好,请在时间过去后接受答复。也看看更新。
    【解决方案2】:

    迟到的答案,但您可以将file_put_contentsFILE_APPEND 标志一起使用,另外,不要使用正则表达式来解析HTML,使用HTML 解析器,如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);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-03
      • 1970-01-01
      • 2020-12-05
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2016-05-14
      相关资源
      最近更新 更多