2015-10-18 163 views
0
$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 Xpath僅獲得所需結果

我是新來的DOM,嘗試了幾件事情,但沒有成功。由於提前

回答

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 
} 
+0

PERFECT !!!非常感謝你 – koca101

+0

@ koca101歡迎你! –