2014-08-29 92 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