PHP DOM not grabbing element

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
walker6o9
Forum Newbie
Posts: 5
Joined: Wed Jul 30, 2008 2:01 pm

PHP DOM not grabbing element

Post by walker6o9 »

I'm trying to grab div id's from html with php dom, but it doesn't seem to be working.

Code: Select all

<html>
<head>
<body>
<div id="area">
HELLO
</div>
</body>
 
</head>
</html>
 

Code: Select all

<?php
 
$doc = new DomDocument;
 
// We need to validate our document before refering to the id
$doc->validateOnParse = true;
$doc->Load('index.html');
 
echo "The element whose id is books is: " . $doc->getElementById('books') . "\n";
 
?>
Last edited by Benjamin on Tue May 26, 2009 12:59 pm, edited 1 time in total.
Reason: Changed code type from text to php.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: PHP DOM not grabbing element

Post by McInfo »

It appears that the easiest way to do it is with XPath.

example-xpath.php

Code: Select all

<?php
header('Content-Type: text/plain');
$doc = new DOMDocument();
$doc->validateOnParse = true;
$doc->loadHTMLFile('./example.html');
$xpath = new DOMXPath($doc);
foreach ($xpath->query("//div[@id='d2']") as $div) {
    echo $div->nodeValue."\n";
}
?>
example.html

Code: Select all

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
        <title>Example</title>
    </head>
    <body>
        <div id="d1">Div 1</div>
        <div id="d2">Div 2</div>
        <div id="d3">Div 3</div>
        <div id="d4">Div 4</div>
    </body>
</html>
Related topic: 100840

Edit: This post was recovered from search engine cache.
Post Reply