2014-08-29 129 views
1

我有一個PHP代碼,它將從「level0 nav-1 active parent」的類名檢索數據。有沒有一種方法可以提供一系列鏈接,併爲每個鏈接的循環數組使用稍微不同的類名,而無需爲10個鏈接重複相同的代碼?從多個鏈接中獲取數據

是這樣的: 第一連桿(https://www.postme.com.my/men-1.html) - 使用類( 「0級NAV-1活性母體」) 二(https://www.postme.com.my/women.html) - 使用類( 「0級NAV-2活性母體」) 三(https://www.postme.com.my/children.html) - 使用類(「level0 nav-3 active parent」)

注意遞增的nav-#?

這是PHP代碼:

<?php 
header('Content-Type: text/html; charset=utf-8'); 
$grep = new DoMDocument(); 
@$grep->loadHTMLFile("https://www.postme.com.my/men-1.html"); 

$finder = new DomXPath($grep); 
$classCat = "level0 nav-1 active parent"; 

$nodesCat = $finder->query("//*[contains(@class, '$classCat')]"); 

$i = 0; 

    foreach ($nodesCat as $node) { 
    $span = $node->childNodes; 
    $replace = str_replace("Items 1-12 of", "",$span->item(1)->nodeValue); 

    echo $replace. " : "; 
    } 

    // Check another link using class name of "level0 nav-2 active parent" 
    //repeat code 

    @$grep->loadHTMLFile("https://www.postme.com.my/women.html"); 

$finder = new DomXPath($grep); 
$classCat = "level0 nav-2 active parent"; 

$nodesCat = $finder->query("//*[contains(@class, '$classCat')]"); 

$i = 0; 

    foreach ($nodesCat as $node) { 
    $span = $node->childNodes; 
    $replace = $span->item(1)->nodeValue; 

    echo $replace. " : "; 
    } 
//check another link with class name "level0 nav-3 active parent". 
//notice the incrementing nav-#? 
//I don't want to make the code long just because each link is using a slightly different class name to refer to the data. 
?> 

感謝

+0

無論如何,您試圖得到什麼特定數據?你需要獲得鏈接(下拉)值文本? – Ghost 2014-08-29 01:19:34

+0

菜單欄中的類別(MEN,WOMEN,KIDS,..) – Cael 2014-08-29 01:22:29

+0

只是爲了澄清?你想從「男性」到「其他」的類別? – Ghost 2014-08-29 01:27:59

回答

1

我會做的就是讓這些鏈接(<li>),這是<ul id="nav">的父。然後從那裏。提取值。例如:

$dom = new DOMDocument(); 
@$dom->loadHTMLFile('https://www.postme.com.my/men-1.html'); 
$xpath = new DOMXpath($dom); 

$categories = $xpath->query('//ul[@id="nav"]/li'); 

foreach($categories as $category) { 
    echo $xpath->query('./a/span', $category)->item(0)->nodeValue . '<br/>'; 
} 
+0

謝謝!還有一件事...有沒有辦法輸出單詞「數組」和數字[0]等?或者當你輸出($ data)時它會聚到一起? – Cael 2014-08-29 02:00:43

+0

@ Cael我只是把它推到一個數組中,這就是爲什麼,我做了一個修改,試試吧 – Ghost 2014-08-29 02:08:16

+0

我希望我能和你一樣好。謝謝! – Cael 2014-08-29 02:14:46