I have PHP snippets like this (snippet.php):
<?php
$some_param = some_function();
?>
<p>
Text, bla bla bla... <?php echo $some_param ?> other text
more text
</p>
I load these snippets like this:
$html = file_get_contets('snippet.php');
$dom = new DOMDocument('1.0');
$dom->loadHTML($html);
and modify using xpath:
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//text()") as $q) {
$str = trim($q->nodeValue);
if (isset($strings[$str])) {
$q->nodeValue = translate($str);
}
}
The problem comes when I try to save this file:
$dom->save($out);
It destroys completly the snippet structure:
<?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>
What can I do to restore the original snippet structure when saving?
The PHP Snippets are Processing Instructions. You can query them with XPath:
How to add them to a document is explained in