我正在创建一个脚本,该脚本从网站获取所有链接并检查每个链接是否已损坏。我的问题是,我需要显示所有已创建的链接,但我需要只验证唯一的链接而不是重复链接。例如,如果一个网站有4个链接到google.com,那么我只想检查一次而不是四次。
foreach ($dom->getElementsByTagName('a') as $node) {
$info = $node->getAttribute( 'href' );
///The function that checks for broken links working.
$check_url_status = check_url($info);
if ($check_url_status == '404') {
$badresult = 'Not working';
}else{
$badresult = 'Working';
}
$showlist .= '<li>The '.$info.' is '.$badresult.'</li>';
}
echo '<ul>'.$showlist.'</ul>';
此代码有效,但我需要让它只检查一次重复链接的http状态。
我不知道如何做到这一点,也有可能做类似的事情。
答案 0 :(得分:1)
您可以创建一个数组,您可以使用该数组保存其中已检查的所有链接。如果链接已经在数组中,您将始终在检查状态之前进行检查。如果是,请跳过链接。如果没有,请检查状态并添加指向阵列的链接。您可以使用关键字continue
跳过元素。
$links = array();
foreach ($dom->getElementsByTagName('a') as $node) {
$info = $node->getAttribute('href');
if(!isset($links[$info])) {
///The function that checks for broken links working.
$check_url_status = check_url($info);
$links[$info] = $check_url_status;
} else {
$check_url_status = $links[$info];
}
if ($check_url_status == '404') {
$badresult = 'Not working';
} else {
$badresult = 'Working';
}
$showlist .= '<li>The '.$info.' is '.$badresult.'</li>';
}
echo '<ul>'.$showlist.'</ul>';
答案 1 :(得分:1)
$newArray = array();
foreach($dom->getElementsByTagName('a') as $node) {
$info = $node->getAttribute('href');
if(!in_array($info, $newArray)) {
$newArray[] = $info;
$check_url_status = check_url($info);
$badresult = ($check_url_status == '404') ? 'Not working' : "Working"
$showlist .= '<li>The '.$info.' is '.$badresult.'</li>';
}
}
你可以启动一个数组,并在它进入条件时将值推入其中,这意味着if the hrefValue is not available into the array
。