我有这个文件:
[playlist]
numberofentries=4
File1=http://108.61.73.119:8128
Title1=(#1 - 266/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
Length1=-1
File2=http://108.61.73.118:8128
Title2=(#2 - 318/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
Length2=-1
File3=http://108.61.73.117:8128
Title3=(#3 - 401/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
Length3=-1
File4=http://198.27.79.224:9770
Title4=(#4 - 27/50) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
Length4=-1
Version=2
我想解析它,只得到文件和标题。问题是parse_ini_file给了我虚假的错误。我尝试了正常的方式,比如解析文本文件,但由于修剪太多,它变得越来越复杂。
有什么想法吗?
php:
$streams = parse_ini_file("tunein-station.pls", true);
print_r($streams);
错误:
PHP Warning: parse error in tunein-station.pls on line 4'n
尝试使用INI_SCANNER_RAW
扫描仪,如下所示:
parse_ini_file('playlist.ini', true, INI_SCANNER_RAW);
这应该能更好地处理带有空格的字符串和不带"
的[]
s。请参阅parse_ini_file()
手册中的扫描仪模式。
或者,您可以对输入文件执行一些预处理,使其成为有效的INI文件:
<?php
// 1. Read your INI file into a string (here we hardcode it for the demo)
$str = <<<EOF
[playlist]
numberofentries=4
File1=http://108.61.73.119:8128
Title1=(#1 - 266/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
Length1=-1
File2=http://108.61.73.118:8128
Title2=(#2 - 318/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
Length2=-1
File3=http://108.61.73.117:8128
Title3=(#3 - 401/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
Length3=-1
File4=http://198.27.79.224:9770
Title4=(#4 - 27/50) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
Length4=-1
Version=2
EOF;
// 2. Add quotes around the "title" values
$str = preg_replace('/^(Title'd+)=(.*)$/m', ''1="'2"', $str);
// 3. Now parse as INI
$array = parse_ini_string($str);
// 4. Here are your results:
print_r($array);
?>
现场演示
输出:
Array
(
[numberofentries] => 4
[File1] => http://108.61.73.119:8128
[Title1] => (#1 - 266/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
[Length1] => -1
[File2] => http://108.61.73.118:8128
[Title2] => (#2 - 318/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
[Length2] => -1
[File3] => http://108.61.73.117:8128
[Title3] => (#3 - 401/1000) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
[Length3] => -1
[File4] => http://198.27.79.224:9770
[Title4] => (#4 - 27/50) 181.FM - POWER 181 -=[: The Hitz Channel :]=- www.181.fm
[Length4] => -1
[Version] => 2
)
这里唯一需要注意的是原始标题值中的双引号;如果需要,可以使用preg_replace_callback
来修复此问题。