Monday, January 16, 2012

Getting content of partial html in DomDocument


I have a string:




$string = 'some text <img src="www">';



I want to get the image source and the text.

Here is what I have:




$doc= new DOMDocument();
$doc->loadHTML($string);
$nodes=$doc->getElementsByTagName ('img');



From $nodes->item(0) I get the image source.

How can I get the the "some text"?

3 comments:

  1. For simple cases like this, try:

    $doc->documentElement->textContent

    ReplyDelete
  2. textContent, or with DOMXPaths $xpath->query('//text()')

    ReplyDelete
  3. You could make it like jQuery in javascript. Wrap the whole string with anything, and get this. Then you can get the TextNode, which contains this text.

    $string = 'some text <img src="www">';
    $string = '<div id="wrapper">' . $string . '</div>';

    $nodes = $doc->getElementById('wrapper');

    ReplyDelete