开发者

PHP DOM Manipulation

I have a template in my DB with a styling, created by the user. Because users are generally stupid and also I don't want them to meddle with php code, I want to insert the actual values into their style before the template is rendered. It's dynamic values.

So I have things like

<p>Here is your value:</p>
<span id="value"></span>
<p>Enjoy it!</p>

A placeholder for the value. This is probably the easiest way. I can't/don't want use jQuery here, but I want something similar.

I've seen PHP's DOMDocument class, which seems to do the trick开发者_开发知识库, with one problem: $dom->saveHTML() seems to be always saving the entire HTML tree. $dom->saveHTML($element) saves just that element, but I have several at once in my template.

Is there a trick to get them all saved without the html stuff around?


saveHTML() saves the element itself and all its children.

You can save the body node to save the whole document content:

$body = $doc->getElementsByTagName('body')->item(0);
$html = $doc->saveHTML($body);

// and remove <body></body>
$html = substr($html, strlen('<body>'), -strlen('</body>'));

Or save body's children one by one:

$html = '';
foreach($body->childNodes as $node) {
    $html .= $doc->saveHTML($node);
}


You can use libxslt's XSLTProc

$html = <<<HTML
<p>Here is your value:</p>
<span id='value'></span>
<p>Enjoy it!</p>
HTML;

$xslt = <<<XSL
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>

<xsl:output encoding='UTF-8' method='html'/>

<xsl:template match='/html/body/*'>
    <xsl:copy-of select='.'/>
</xsl:template>

</xsl:stylesheet>
XSL;

$htmldoc = new DOMDocument();
$htmldoc->loadHTML($html);
$xsltdoc = new DOMDocument();
$xsltdoc->loadXML($xslt);

$xsltproc = new XSLTProcessor();
$xsltproc->importStylesheet($xsltdoc);
print $xsltproc->transformToXML($htmldoc);

Output:

<p>Here is your value:</p>
<span id='value'></span>
<p>Enjoy it!</p>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜