-4

我有这个查询,它从两个不同的元素中获取两个值,一个是包含一些内容的 div,一个是链接

$tableRows = $xpath->query('//div[@id="div1"]/div[@id="div2"]/div[1] | 
//div[@id="div1"]/div[@id="div2"]/div[3]//div[a][1]');
foreach ($tableRows as $row) {
echo $row->nodeValue,"<br><br>";
}

现在它正在输出 div 内容和链接的锚文本,我希望能够将 div 内容存储到一个变量中,并将链接的 href 值存储在另一个变量中,我该怎么做

编辑

$div = array();
$link = array();
$div = $xpath->query('//div[@id="div1"]/div[@id="div2"]/div[1]'); 
$link = $xpath->query('//div[@id="div1"]/div[@id="div2"]/div[3]//div[a][1]//@href');
$k=0;
$i = count($div);
while($k<=$i){
echo $div->items[$k]->nodeValue.'<br><br>';
echo $link->items[$k++]->nodeValue.'<br><br>';
}

只是黑屏

具有真实 div id 等的完整代码

$curl = curl_init('http://mp3skull.com/mp3/psy.html'); //example 'psy' will eventually be a variable looped
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10');
$html = curl_exec($curl);
curl_close($curl);


$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$div = array();
$link = array();
$div = $xpath->query('//div[@id="song_html"]/div[@id="right_song"]/div[1]');
$link = $xpath->query('//div[@id="song_html"]/div[@id="right_song"]/div[3]//div[a]   [1]//@href');
$k=0;
$i = count($div);
while($k<=$i){
echo $div->items[$k]->nodeValue.'<br><br>';
echo $link->items[$k++]->nodeValue.'<br><br>';
}
4

1 回答 1

0
    <?

    $curl = curl_init('http://mp3skull.com/mp3/psy.html'); //example 'psy' will eventually be a variable looped
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10');
    $html = curl_exec($curl);
    curl_close($curl);


    $dom = new DOMDocument();
    @$dom->loadHTML($html);

    $xpath = new DOMXPath($dom);

    $div_array = array();
    $link_array = array();
    $div = $xpath->query('//div[@id="song_html"]/div[@id="right_song"]/div[1]');
    $link = $xpath->query('//div[@id="song_html"]/div[@id="right_song"]/div[3]//div[a][1]//@href');



    for ($i = 0; $i < $div->length; $i++) {
         array_push($div_array, $div->item($i)->nodeValue);
    }
    for ($i = 0; $i < $link->length; $i++) {
         array_push($link_array, $link->item($i)->nodeValue);
    }
    $i = 0;
    $m = count($div_array);


    while ($i<=$m)
    {
    echo $div_array[$i].'<br><br>'; 
    echo $link_array[$i++].'<br><br>';  
    }

    ?>
于 2013-07-18T19:14:09.230 回答