$some_link = 'http://www.example.com';
$abc = 'killer';
$bcd = 'awsome';
$cde = 'qwerty';
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTMLFile($some_link);
$html = getTags( $dom, $abc, $bcd, $cde );
echo $html;
function getTags( $dom, $abc, $bcd, $cde ){
$html = '';
$domxpath = new DOMXPath($dom);
$newDom = new DOMDocument;
$newDom->formatOutput = true;
$defffff = $domxpath->query("//$abc" . '[@' . $bcd . "='$cde']");
// since above returns DomNodeList Object
// converting to string(html)
$i = 0;
while( $myItem = $defffff->item($i++) ){
$node = $newDom->importNode( $myItem, true ); // import node
$newDom->appendChild($node); // append node
}
$html = $newDom->saveHTML();
return $html;
}
?>
这是整个代码。它连续返回多个结果,现在我想要的只有结果no.1和no.5。我该怎么办?
我是DOM新手,尝试了几件事但没有成功。在此先感谢
答案 0 :(得分:1)
更改此
$i = 0;
while( $myItem = $defffff->item($i++) ){
$node = $newDom->importNode( $myItem, true ); // import node
$newDom->appendChild($node); // append node
}
进入此,以append
仅选择节点
$i = 0;
while( $myItem = $defffff->item($i++) ){
if ($i==0 or $i==4){
$node = $newDom->importNode( $myItem, true ); // import node
$newDom->appendChild($node); // append node
}
}
或者如果你知道你想要的索引,你可以这样做
$myIndexes = array (0,4);
foreach ($myIndexes as $i){
$myItem = $defffff->item($i++);
$node = $newDom->importNode( $myItem, true ); // import node
$newDom->appendChild($node); // append node
}