0

我有一个混合了 html、文本和 php 的 PHP 文件,包括名称 areaname-house.php。文件的 text/html 部分在不同位置包含字符串“areaname”。另一方面,我有一组带有城市名称的字符串。

我需要一个 PHP 脚本,它可以获取每个字符串(来自字符串数组),复制 areaname-house.php 并创建一个名为 arrayitem-house.php 的新文件,然后在新创建的文件中,将字符串“areaname”替换为数组项。我已经能够完成第一部分,我可以使用示例变量(城市名称)成功创建克隆文件作为以下代码中的测试:

    <?php
    $cityname = "acton";
    $newfile = $cityname . "-house.php";
    $file = "areaname-house.php";

    if (!copy($file, $newfile)) {
        echo "failed to copy $file...n";

    }else{

        // open the $newfile and replace the string areaname with $cityname

    }

?>
4

1 回答 1

6
$content = file_get_contents($newfile);
$content = str_replace('areaname', $cityname, $content);
file_put_contents($newfile, $content);

更容易的是......

$content = file_get_contents($file); //read areaname-house.php
$content = str_replace('areaname', $cityname, $content);
file_put_contents($newfile, $content); //save acton-house.php

所以你不需要显式地复制文件。

于 2009-08-15T07:48:49.193 回答