3

我有这个文件:

[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
4

2 回答 2

4

尝试使用INI_SCANNER_RAW扫描仪,如下所示:

parse_ini_file('playlist.ini', true, INI_SCANNER_RAW);

这应该更好地处理带有空格和[]s 的字符串,而不是"更好地围绕它们。请参阅手册中的扫描仪模式parse_ini_file()

于 2013-08-11T17:56:19.397 回答
0

或者,您可以对输入文件执行一些预处理以使其成为有效的 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如果需要,您可以使用它来解决此问题。

于 2013-08-11T18:04:50.423 回答