我的示例代码在这里
include 'simple_html_dom.php';
function get_all_links($url){
global $host;
$html = new simple_html_dom();
$html->load(file_get_contents($url));
foreach($html->find('a') as $a){
$host1 = parse_url($a->href);
$host = parse_url($url);
if($host1['host'] == $host['host']){
$data[] = $a->href;
}
}
return $data;
}
$links = get_all_links("http://www.example.com/");
foreach($links as $link){
echo $link."<br />";
}
当我尝试这段代码时,我得到了这个错误: Notice: Undefined index: host in... 我的代码有什么问题?请给我一些帮助代码,在此先感谢。
最佳答案
您需要使用 isset
检查数组是否包含 'host'
的条目|在假设它们存在之前:
if (isset($host1['host']) && isset($host['host'])
&& $host1['host'] == $host['host']) {
或者你可以 use @
to suppress warnings来自支票。
if (@$host1['host'] == @$host['host']) {
但是,当两者都缺失时,您需要仔细检查后者是否按您希望的方式工作。
更新: 正如其他人指出的那样,还有 array_key_exists
.它将处理 null
数组值,而 isset
为 null
值返回 false
。
关于php - 为什么我收到此错误通知 : Undefined index: host,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9882794/