php - 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);
}
?>
请注意:
- Links.txt 文件包含多个外部 URL,每一行只有一个 URL。例子:
www.External-URL-number-ONE.com
www.External-URL-number-TWO.com
www.External-URL-number-THREE.com
- 每个 URL 在变量 $content 中都有“title”项(在用“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() 在访问数组之前检查它。并且只有每个循环的最后一个有索引。
解决方案
读取文件并逐行读取
<?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];
}
?>
推荐阅读
- r - 清除所有绘图,现在 ggplot2 不会绘图
- python - python:如何从两个不同的列表中取出列表中的第一个列表并将它们配对以使它们成为单独的列表
- list - 在 Python 列表中进行就地修改
- javascript - 如何在 TypeScript 中使用 Wix Style React 组件?
- c# - 将 SafeFileHandle 与 FileStream 构造函数一起使用有什么好处吗
- php - 从 crontab (Nagios) 执行 PHP 脚本的 SSH 问题
- c++ - 重新散列时锁定散列映射
- java - 从 Java 中的 URL 获取值
- python - 我们需要找到两条对角线之和之间的绝对差。请你能告诉我哪里出错了吗
- rust - 将模块存储为 rust 中的变量