Jump to content

[SOLVED] Getting the contents of a certain div.


Michdd

Recommended Posts

After reading a little more about the DOM class it seems like it might be the better method. It looks a bit like javascript. 'getElementById'. However how can I get the contents of that div?:

 

$doc = new DomDocument;
$doc->validateOnParse = true;
$doc->Load($_GET['page'] . '.php');

echo $doc->getElementById('center');

 

Of course that won't work, but is there another pointer to get the contents of that div?

regex is not really good for that sort of thing.  It does not handle nested tags very well.  Stick with DOM.

Okay, then can you answer my above question? Can I get the html contained in an element from getElementById? In Javascript it would be .innerHTML, but I can't find the PHP equiv.

<?php
function getInnerHTML(DOMElement $node)
{
$body = $node->ownerDocument->documentElement->firstChild->firstChild;
$document = new DOMDocument();    
$document->appendChild($document->importNode($body,true));
return $document->saveHTML();
}

$doc = new DOMDocument();
$doc->LoadHTMLFile('http://www.phpfreaks.com/');

echo getInnerHTML($doc->getElementById('header'));

 

Output:

<title>PHP Freaks - Index</title>

That seems to be only outputting:

 

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 

(which isn't even within that div)

 

When I'm trying to get the contents of the <div id="center"> on page 'about.php' using:

 

<?php
function getInnerHTML(DOMElement $node)
{
$body = $node->ownerDocument->documentElement->firstChild->firstChild;
$document = new DOMDocument();    
$document->appendChild($document->importNode($body,true));
return $document->saveHTML();
}

$doc = new DOMDocument();
$doc->LoadHTMLFile('about.php');

echo getInnerHTML($doc->getElementById('center'));

Sorry, something like this:

 

$doc = new DOMDocument();
$doc->LoadHTMLFile('http://www.phpfreaks.com/');

$d = new DOMDocument();
$d->appendChild($d->importNode($doc->getElementById('header'), true));

$html = trim(preg_replace('#(^<[^>]+>|</[^>]+>$)#', '', $d->saveHTML()));

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.