doushi2047 2013-11-03 19:53
浏览 121

在PHP中将DOM字符串添加到DOMDocument

I have a DOMDocument object and I want to manipulate text nodes and return them to the object as a HTML string. For example:

$dom=new DomDocument();
$dom->loadHTML('<html><body>This is [b]BBC[/b]</body></html>');

// $node is a text node
$html=parseBBC($node->nodeValue);
$frag=$dom->createDocumentFragment();
$frag->appendXML($html);
$node->parentNode->replaceChild($frag,$node);

echo $dom->saveHTML();

Expected output:

<html><body>This is <b>BBC</b></body></html>

Actual output:

empty string

Edit:

$dom=new DomDocument();
$dom->loadHTML('<html><body>This is[br]BBC</body></html>');
$xpath=new DOMXPath($dom);

$r=$xpath->query('//text()');
foreach($r as $el){
  $str=trim(str_replace('[br]',"
",$el->nodeValue));
  $str='<p>'.preg_replace('/(
|)+/','</p><p>',$str).'</p>';
  $frag=$dom->createDocumentFragment();
  $frag->appendXML($str);
  $el->parentNode->replaceChild($frag,$el);
}

echo $dom->saveHTML();
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 matlab有关常微分方程的问题求解决
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?
    • ¥100 求三轴之间相互配合画圆以及直线的算法
    • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
    • ¥15 名为“Product”的列已属于此 DataTable