首页 > 解决方案 > PHP 对于每个循环,parse_str 接收“通知:未定义索引:标题”

问题描述

我有以下 PHP 代码:

<?php
$file = "Links.txt";
$parts = new SplFileObject($file); // this is your array of words

foreach($parts as $word) {
    $content = file_get_contents($word);
    parse_str($content, $ytarr);
    echo $ytarr['title'];
    unset($content);
}
?>

请注意:

www.External-URL-number-ONE.com

www.External-URL-number-TWO.com

www.External-URL-number-THREE.com

错误信息和结果:

注意:未定义索引:第 13 行 C:\xampp\htdocs\PHPexample\index.php 中的标题

显示“www.External-URL-number-THREE.com”的标题

我该如何解决这个问题?它也应该适用于多行。

提前致谢。

编辑:

变量的内容$content是:

大批 (

[reason] => Invalid parameters.

[status] => fail

[errorcode] => 2

)

大批 (

[ISD] => 928398

[enable] => 1

[list] => 39/9339/30

[AMP] => 

[host] =>     

[title] => This_Is_the_Title_Three

[token] => 1

)

更新

我使用 isset() 在访问数组之前检查它。并且只有每个循环的最后一个有索引。

标签: phparraysloops

解决方案


读取文件并逐行读取

<?PHP 
$file = "Links.txt";
$handle = @fopen($file, "r");

if ($handle) {
    // Read line by line
    while (($word = fgets($handle)) !== false) {
        $content = file_get_contents($word);

        // parse_str($content, $ytarr);  // parse_str don't work in this case
        //echo @$ytarr['title'];
        //unset($content);

        echo getDataTag($content, 'title');
    }
    fclose($handle);
}


//This is a dirty solution
function getDataTag($str, $tag){
    $str = str_replace('+',' ',$str);
    $data = explode(($tag.'='),$str);
    $data = explode('&',$data[1]);
    return $data[0];
}

?>

推荐阅读