2013-03-07 18 views
1

我们在文件夹“music”中有700个静态HTML文件。我们希望把分析代码放在HTML文件的末尾..像以前一样如何用PHP更新静态HTML文件

</body> </html> 

标签。

请有人让我知道,它如何可能与PHP代码?

+2

遍历该目录下的文件,依次打开每个使用的DomDocument注入所需的附加标记,并写回相同的文件名 – 2013-03-07 10:01:20

+0

你也可能要考虑您的数据存储和移动你的内容到一种数据库并从中产生你的静态文件。 – Thomas 2013-03-07 10:02:52

+0

是否要添加一些html代码或php代码? – zkanoca 2013-03-07 10:05:24

回答

2

太容易了。查找所有文件,阅读内容,修改内容,保存内容。

<?php 

// open directory 
if($handle = opendir(__DIR__)) { 
    // search for 
    $search = '</body>'; 

    // replace with (</body> gets appended later in the script) 
    $replace = <<< EOF 

<!-- your analytics code here --> 

EOF; 

    // loop through entries 
    while(false !== ($entry = readdir($handle))) { 
     if(is_dir($entry)) continue; // ignore entry if it's an directory 

     $content = file_get_contents($entry); // open file 
     $content = str_replace($search, $replace . '</body>', $content); // modify contents 
     file_put_contents($entry, $content); // save file 
    } 
} 

echo 'done'; 

?> 
+0

你可能是指'str_replace'而不是'preg_replace',因为'$ search'的内容。 – cmbuckley 2013-03-07 10:09:44

+0

@cbuckley啊是的!我改变了代码。 – 2013-03-07 10:18:18

+0

我把index.php文件放在我的html文件夹中,当我测试这段代码时,html文件是空白的,它的显示Warning:file_put_contents()期望至少有2个参数,1在C:\ wamp \ www \ html \第25行的index.php, – 2013-03-07 10:25:12