I'd probably use either of these two approaches, where the first one is pretty much the XPath equivalent of NogDog's method chaining. I simply find the XPath easier to read. The second one uses getElementById to get a context node for a shorter XPath.
$d = new DOMDocument();
$d->loadHTML($html);
$xp = new DOMXPath($d);
$ids = array('item1', 'item2', 'item4', 'item5');
foreach ($ids as $id)
{
$q = sprintf('/html/body/div[@id="page"]/div[@id="body"]/div[@id="%s"]/div/div[@class="value"]',
$id
);
$nl = $xp->query($q);
if ($nl->length)
{
printf('Found "%s"<br>', $nl->item(0)->nodeValue);
}
else
{
printf('Failed matching for id="%s"<br>', $id);
}
}
$q = 'div/div[@class="value"]';
foreach ($ids as $id)
{
if ($el = $d->getElementById($id))
{
$nl = $xp->query($q, $el);
if ($nl->length)
{
printf('Found "%s"<br>', $nl->item(0)->nodeValue);
}
else
{
printf('No value for id="%s"<br>', $id);
}
}
else
{
printf('No element with id="%s"<br>', $id);
}
}