在文件中添加一行

时间:2016-02-16 18:32:50

标签: php file foreach preg-replace

所以我有这个自动生成的HTML文件。 http://pastebin.com/mTMJNrdm

我正在尝试用这个替换第5行的PHP脚本。

<LINK href="style.css" rel="stylesheet" type="text/css"></style>

我试图绕过它,因为它是一个文件。什么功能可以为我完成这个?

当前代码:

$fh = file('standings.html');

$css = addslashes('<LINK href="style.css" rel="stylesheet" type="text/css"></style>');

$pattern = "</style>";

foreach ($fh as $lines) {
     if (preg_match($pattern, $lines)) {
         // Replace this line with $css
     }
}

2 个答案:

答案 0 :(得分:2)

php file函数已将整个文件读入数组。只需通过指定所需的索引替换所需的行:

$lines = file('standings.html');

$lines[4] = addslashes('<LINK href="style.css" rel="stylesheet" type="text/css"></style>');
$new_content = implode(" ", $lines);

file_put_contents('standings.html', $new_content);

答案 1 :(得分:0)

检查此代码,我评论fopen和fwrite,检查文件permisions并取消注释。

<?php
$dom = new DOMDocument;

$dom->loadHTMLFile('file.html');


$elements = $dom->getElementsByTagName('style');

for ($i = $elements->length; --$i >= 0; ) {
    $s = $elements->item($i);


    $element = $dom->createElement('style', '');
    $domAttribute = $dom->createAttribute('href');
    $domAttribute->value = 'style.css';
    $element->appendChild($domAttribute);

    $domAttribute = $dom->createAttribute('rel');
    $domAttribute->value = 'stylesheet';
    $element->appendChild($domAttribute);

    $domAttribute = $dom->createAttribute('type');
    $domAttribute->value = 'text/css';
    $element->appendChild($domAttribute);

    $s->parentNode->replaceChild($element, $s);

}
$html = $dom->saveHTML();

/*
$file = fopen("file.html", "w+");
fwrite($file, $html);
*/

print_r("<pre>");
print_r($html);
print_r("</pre>");
die;