php - 为什么我收到此错误通知 : Undefined index: host

标签 php

我的示例代码在这里

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 数组值,而 issetnull 值返回 false

关于php - 为什么我收到此错误通知 : Undefined index: host,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9882794/

相关文章:

PHP如何使用 key 编码/解码文本?

php - 计算特定 ID 的行数

php - Magento - 以编程方式将选项分配给多选属性

php - Mysql 没有返回预期结果

php - 我们有任何 php 应用程序服务器(不是网络服务器)吗?

javascript - 我有一个 div,它需要动态复制

javascript - Braintree 上未知的 paymentMethodNonce

php - 循环中的错误数组值

php - 使用 PHP 在屏幕上创建点

php - Magento更新每商店价格查看SQL