我有这样的 PHP 片段(snippet.php
):
<?php
$some_param = some_function();
?>
<p>
Text, bla bla bla... <?php echo $some_param ?> other text
more text
</p>
我像这样加载这些片段:
$html = file_get_contets('snippet.php');
$dom = new DOMDocument('1.0');
$dom->loadHTML($html);
并使用 xpath 进行修改:
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//text()") as $q) {
$str = trim($q->nodeValue);
if (isset($strings[$str])) {
$q->nodeValue = translate($str);
}
}
当我尝试保存此文件时出现问题:
$dom->save($out);
它完全破坏了片段结构:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><head><?php
$some_param = some_function();
??></head><body><p>
Translated text, bla bla bla... <?php echo $some_param ?> other text
more text
</p></body></html>
保存时如何恢复原始代码段结构?