Wat @Ward zei, schrijf een soort van trace functie die je ook informatie teruggeeft over waar het misgaat, zoiets dus:
<?php
// include simple_html_dom hier ergens
// ...
ob_start();
?><h2>random header</h2>
<p>introducution</p>
<div id="tree">
<ul>
<li>1<ul>
<li>1.1<ul>
<li>1.1.1<ul>
<li>1.1.1.1</li>
</ul></li>
<li>1.1.2</li>
</ul></li>
</ul></li>
<li>2</li>
<li>3<ul>
<li>3.1</li>
<li>3.2<ul>
<li>3.2.1</li>
<li>3.2.2</li>
</ul></li>
</ul></li>
</ul>
</div><?php
$input = ob_get_clean();
$html = str_get_html($input);
$tree = $html->find('div[id=tree] ul', 0); // returns an array of simple_html_dom_node's
$test = $tree->children(0)->children(0)->children(0)->children(0)->children(0)->next_sibling();
echo $test->innertext().'<hr>'; // 1.1.2
$trace = array(
array('c', 0), // children, index 0
array('c', 0), // children, index 0
array('c', 0), // children, index 0
array('c', 0), // children, index 0
array('c', 0), // children, index 0
array('n'), // next sibling
);
function domTrace($in, $trace) {
$step = 0;
foreach ($trace as $action) {
switch ($action[0]) {
case 'c': // children
if (method_exists($in, 'children')) {
if (isset($action[1])) { // was an index provided?
$in = $in->children($action[1]);
} else {
$in = $in->children();
}
if ($in === NULL) {
throw new Exception('children not found in step '.$step);
}
} else {
throw new Exception('method children does not exist in step'.$step);
}
break;
case 'n': // next_sibling
$in = $in->next_sibling();
if ($in === NULL) {
throw new Exception('sibling not found in step '.$step);
}
break;
default: throw new Exception('unknown op in step '.$step);
}
$step++;
}
return $in;
}
try {
$test = $tree;
$test = domTrace($test, $trace);
echo $test->innertext(); // 1.1.2
} catch (Exception $e) {
echo $e->getMessage();
}
?>[end]
En als je de foutmeldingen stilzwijgend wil afhandelen zou je
false kunnen retourneren in plaats van het throwen van een Exception.
Link gekopieerd