每个循环的PHP,parse_str收到“注意:未定义的索引:标题”

时间:2018-11-29 23:31:17

标签: php arrays loops

我有以下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);
}
?>

请注意:

  • Links.txt文件包含多个外部URL,每行只有一个URL。示例:
  

www.External-URL-number-ONE.com

     

www.External-URL-number-TWO.com

     

www.External-URL-number-THREE.com

  • 此URL中的每个URL在变量$ content中都有“标题”项(在用“ file_get_contents($ word);填充它之后”。)。
  • 出于故障排除的目的,我通过将每个URL添加到“ links.txt”中来测试了每个URL。结果是每个URL成功。如果我添加多个URL,则会出现此问题。在这种情况下,其行为是:

错误消息和结果:

  

注意::未定义的索引:第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()检查数组。而且每个循环的最后一个都有索引。

1 个答案:

答案 0 :(得分:0)

读取文件并逐行读取

<?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];
}

?>