我有一个循环,我想推送第一个 div 元素的第一个 a 元素的 nodeValue 和 href。我是 DOM 新手,所以我阅读了几篇文章并提出了以下代码。不幸的是,这不起作用。希望有人可以帮助我解决这个问题。预先感谢您的回复。干杯。马克
下面是 $value 的 html 结构(请参阅下面的循环以了解 $value 是什么)
<body>
<div>
<a href="myhreflink">this is my target</a>
<a href="somehref">sometext</a>
</div>
<div></div>
<div></div>
<div></div>
</body>
在我的循环下面:
myarray = array();
/* $content is a DOMNodeList Object and $value is a DOMElement Object */
foreach ($content as $value){
$firstDiv = $value->getElementsByTagName('div')[0];
$firstA = $firstDiv->getElementsByTagName('a')[0];
$val = $firstA->nodeValue;
$link = $firstA->getAttribute('href');
array_push($myarray, array('val'=>$val, 'href'=>$link));
}
-> 下面是完整的代码----------
<?php
header('Content-Type: text/html; charset=utf-8');
mysql_set_charset('utf8');
ini_set('display_errors', 1); error_reporting(E_ALL);
$liste = array();
$url = 'myurl';
$path = 'mypath';
$titres = print_url_data($url, $path);
foreach($titres as $value){
array_push($liste, $value);
}
// -> functions ------------------------------------------------------------
function print_url_data($url, $path){
$content = get_url_data($url, $path);
$tableau = array();
foreach ($content as $value){
$firstDiv = $value->getElementsByTagName('div')->item(0);
$firstA = $firstDiv->getElementsByTagName('a')->item(0);
$val = $firstA->nodeValue;
$link = $firstA->getAttribute('href');
array_push($myarray, array('val'=>$val, 'href'=>$link));
}
return $tableau;
}
function get_url_data($url, $path){
$xml_content = get_url($url);
$dom = new DOMDocument();
@$dom->loadHTML($xml_content);
$xpath = new DomXPath($dom);
$content_title = $xpath->query($path);
return $content_title;
}
function get_url($url){
$curl = curl_init();
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_REFERER, '[url=http://www.google.com]http://www.google.com[/url]');
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$html = curl_exec($curl);
curl_close($curl);
return $html;
}
?>