1

I'm trying to replace all td cells text to include link tag. Currently with the code below, the cells are being replaced but when I output the table, it literally just output the html code like so:

<a href="sdf" class="link">Some text</a>

Instead of a real physical HTML link. How do I actually replace a nodeValue with HTML tags? Thanks.

$DOM = new DOMDocument( );
@$DOM->loadHTML( $htmlTable );
$DOMXPath = new DOMXPath( $DOM );

$cellName = $DOMXPath->query('//td[contains(@class,"classA")]');

foreach( $cellName as $text ) {
    $text->nodeValue = '<a href="sdf" class="link">' . htmlspecialchars( trim( $text->nodeValue ) ) . '</a>';
}
4
  • Try foreach( $cellName as &$text ) { and tell if it worked Commented Jun 5, 2013 at 6:53
  • Possible duplicate of stackoverflow.com/questions/7857595/… Commented Jun 5, 2013 at 6:58
  • Thanks, but doesn't work (iterator cannot be use for foreach by refence). Commented Jun 5, 2013 at 6:59
  • Not a duplicate issue though. Can't find a workaround with this anywhere Commented Jun 5, 2013 at 7:02

1 Answer 1

1

Finally got it to work. In case it helps anyone. In order to change a text node with HTML inside a td value, use the following:

$partial = $DOM->createDocumentFragment();
$partial->appendXML('<a href="sdf" class="link">some text</a>');
$text->parentNode->replaceChild($partial, $text );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.