I am trying to learn using DOMDocument for parsing HTML code.
I am just doing some simple work, I already liked gordon\'s answer on scrap data using regex and simpl
Here is how you could do it with DOM and XPath:
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTMLFile('http://www.nu.nl/…');
libxml_clear_errors();
$xpath = new DOMXPath($dom);
echo $xpath->evaluate('string(id("leadarticle")/div/h1)');
echo $dom->saveHtml(
$xpath->evaluate('id("leadarticle")/div[@class="content"]')->item(0)
);
The XPath string(id("leadarticle")/div/h1)
will return the textContent of the h1 that is a child of a div that is the child of the element with the id leadarticle.
The XPath id("leadarticle")/div[@class="content"]
will return the div with the class attribute content that is a child of the element with the id leadarticle.
Because you want the outerHTML of the content div you'll have to fetch the entire node and not just the content, hence no string() function in the XPath. Passing a node to the DOMDocument::saveHTML() method (which is only possible as of 5.3.6) will then serialize that node back to HTML.