2

The div is like this

<div style="width:90%;margin:0 auto;color:#Black;" id="content">
this is text, severaltags
</div> 

how should i get the div's content including the
tags using dom in php?

xkeshav
  • 53,360
  • 44
  • 177
  • 245
David
  • 2,691
  • 7
  • 38
  • 50

4 Answers4

4

Assuming your using PHP5 you can use DOMDocument -- take note that this doesn't provide simple means for retrieving inner html of an element. You can do something along the following:

function DOMinnerHTML($element) 
{ 
    $innerHTML = ""; 
    $children = $element->childNodes; 
    foreach ($children as $child) 
    { 
        $tmp_dom = new DOMDocument(); 
        $tmp_dom->appendChild($tmp_dom->importNode($child, true)); 
        $innerHTML.=trim($tmp_dom->saveHTML()); 
    } 
    return $innerHTML; 
} 

$dom = new DOMDocument();

$dom->loadHTML($html);

$items = $dom->getElementsByTagName('div');
if ($items->length)
{
    $innerHTML = DOMinnerHTML($items->item(0));
}

echo $innerHTML;

For something this simple, although I don't normally recommend it, I'd use regex:

preg_match('|<div[^>]+>(.*?)</div>|is', $html, $match);

if ($match)
{
    echo 'html is: ' . $match[1][0];
}
Gary Green
  • 22,045
  • 6
  • 49
  • 75
  • Nice approach. In your DOMinnerHTML function, you could use the ownerDocument(associated DOMDocument Object) property that is already defined for every DOMNode and DOMElement objects. i.e. you could just put in your foreach loop : `$innerHTML .= $child->ownerDocument->saveXML( $child );` [source](http://www.php.net/manual/de/class.domelement.php#101243) – Yann Milin May 03 '11 at 08:17
  • Nice katsuo! Didn't know about ownerDocument – Gary Green May 03 '11 at 08:20
  • yeah! it's pretty handy! That's why I wanted to mention it here. – Yann Milin May 03 '11 at 08:22
1

Something like this?

$document = new DOMDocument();
$document->loadHTML($html);

$element = $document->getElementById('content');
Svish
  • 152,914
  • 173
  • 462
  • 620
1

To get the values, you can try something like this

$doc = new DOMDocument();
$doc->loadHTMLFile('link-t0-html-file.php');
$xpath = new DOMXPath($doc);
$element = $xpath->query("//*[@id='content']")->item(0);
echo $element->nodeValue;
Starx
  • 77,474
  • 47
  • 185
  • 261
0

if i am not wrong you want this

echo "< div style='width:90%;margin:0 auto;color:#000000;font-size:14px;line-height:24px;' 
id='content'>";

echo "this is text, several `<br/>` tags";

echo "< /div>"; 

just mind it never use double quote (") within double quote ("). use single quote(') within double quote.

Ariful Islam
  • 7,639
  • 7
  • 36
  • 54