1

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]',"\n",$el->nodeValue));
  $str='<p>'.preg_replace('/(\n|\r)+/','</p><p>',$str).'</p>';
  $frag=$dom->createDocumentFragment();
  $frag->appendXML($str);
  $el->parentNode->replaceChild($frag,$el);
}

echo $dom->saveHTML();
Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • 1
    What does `parseBBC` do? And in particular, what does it return which ends up in `$html`? – IMSoP Nov 03 '13 at 19:56
  • It just returns a string with HTML. For example: `This is BBC` – Leo Jiang Nov 03 '13 at 19:58
  • Pls provide all code necessary to understand what's going on. – michi Nov 03 '13 at 20:48
  • Check the edited section. I removed the `parseBBC()` function. I thought it was obvious that it parses BBCode and returns HTML. – Leo Jiang Nov 03 '13 at 20:54
  • You have a comment that says `// $node is a text node` but you don't actually show any code where `$node` comes from. Either this isn't an actual tested example of the problem, or you have a "White Page of Doom" and need to [check error logs or adjust your error display settings](http://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php/12772851#12772851) – IMSoP Nov 03 '13 at 21:22
  • I added `echo $dom->saveHTML();die;` after each line, and the problem lies in `$el->parentNode->replaceChild($frag,$el);` – Leo Jiang Nov 03 '13 at 21:46
  • The second example works fine - outputs `

    This is

    BBC

    `.
    – Alf Eaton Nov 05 '13 at 13:41

0 Answers0