【问题标题】:How to echo value from one file to another file while copying or writing in PHP?如何在 PHP 中复制或写入时将值从一个文件回显到另一个文件?
【发布时间】:2018-10-03 23:05:16
【问题描述】:

我想写和复制一个文件。而且我在写入和复制文件时需要echo 值。

请检查我的代码:

<?php 
$pages = array("story1", "story2", "story3","story4","story5","story6");
$length = count($pages);

for($i=0;$i<$length;$i++){
    $myFile = "newfile-in-{$pages[$i]}.php";

    if (file_exists($myFile)) {
        echo copy("expcontent.php","newfile-in-{$pages[$i]}.php");
    }else{
        $myfile = fopen("newfile-in-{$pages[$i]}.php", "w") or die("Unable to open file!"); 

        $txt = "Mickey {$pages[$i]}\n";
        fwrite($myfile, $txt);
        $txt = "Hello Mouse\n";
        fwrite($myfile, $txt);
    }
}

在我的expcontent.php

<p>Kids <?php echo $pages[$i];?>!</p>

一切正常。新文件已创建并已完美复制文件。但输出是:

Kids, !   
Kids, !   
Kids, !   
Kids, !   
Kids, !   

预期输出:

Kids Story1!
Kids Story2!
Kids Story3!
Kids Story4!
Kids Story5!
Kids Story6!

我没有得到正确的输出,或者我认为$pages[$i] 的值在expcontent.php 上。

请检查我的代码并纠正我。 欢迎任何想法或建议。 谢谢。

【问题讨论】:

  • 复制文件不会执行其中的 PHP。它只是逐字复制。
  • 看起来您正在尝试实现某种模板系统。有许多库和框架可以做到这一点,您应该使用其中之一,而不是尝试使用自己的。
  • @Barmar 感谢您的回复!在写文件的时候?在写文件的同时,我们可以写孩子们的故事1!如果是怎么办?
  • @RachelGallen 只要PHP下面没有HTML/CSS等,就不需要使用?&gt;结束标签。
  • @FunkFortyNiner 啊对。错过了。谢谢。

标签: php html arrays file


【解决方案1】:

阅读问题下的 cmets [除了问题],我了解到您想通过写出文件内容来扩展故事,而不仅仅是文件名。

如果您已创建故事的“章节”并将它们存储为单独的文件,则可以使用include 写出内容:

例如

<?php
    $title="My Kids Story";
    include "chapter1.php";
    include "chapter2.php";
?>

您可以将章节存储为 .php 或者您可以使用备用扩展名并在服务器配置 (httpd.confon apache) 文件中阻止 [来自用户] 直接访问它。 More about that here

例如把它放在你的配置中并包含 chapter1.inc 而不是 .php

<Files ~ "\.inc$">
  Order allow,deny
  Deny from all
</Files>

【讨论】:

  • p.s 查看chapter 9 以查看合并变量值的示例函数
【解决方案2】:

您只是在复制文件,但它永远不会执行。您可以读取文件内容并使用eval 执行它。请务必查看文档。

注意 eval() 语言结构非常危险,因为它允许 执行任意 PHP 代码。因此不鼓励使用它。如果你 已经仔细验证除了使用这个没有其他选择 构造,特别注意不要传递任何用户提供的数据 在没有事先正确验证的情况下进入它。

$pages = array("story1", "story2", "story3","story4","story5","story6");

foreach ($pages as $page) {
  $myFile = "newfile-in-{$page}.php";

  if (file_exists($myFile)) {
    $content = file_get_contents('expcontent.php');
    $newcontent = eval($content);
    file_put_contents($myFile, $newcontent);
  } else {
    $myfile = fopen("newfile-in-{$page}.php", "w") or die("Unable to open file!"); 
    $txt = "Mickey {$page}\n";
    fwrite($myfile, $txt);
    $txt = "Hello Mouse\n";
    fwrite($myfile, $txt);
  }
}

再次从手册中:

代码不得包含在打开和关闭 PHP 标记中。

因此,您必须将您的 expcontent.php 更改为:

?><p>Kids <?php echo $page;?>!</p>

echo "<p>Kids {$page}!</p>";

不使用 eval 的另一种更安全的方法是捕获第二页的输出(这只是 if 块,它应该与您原来的 expcontent.php 一起使用)。

ob_start();
include 'expcontent.php';
$content = ob_get_clean();
file_put_contents($myFile, $content);

【讨论】:

  • 感谢您的回复。但即使它删除了我所有的内容也没有用,即:儿童故事 2!并且文件大小减少了 24b 到 0b
  • @Sarah 抱歉,这里有一个 coupe 错误,但应该可以工作。
猜你喜欢
  • 2014-08-23
  • 2020-07-30
  • 2016-12-28
  • 2018-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多