0

I have a string pulling from a socket: (it is a single string with no escapes (/r/n))

PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
X-CALENDARSERVER-ACCESS:PUBLIC
BEGIN:VTIMEZONE
TZID:Pacific Time
BEGIN:STANDARD
DTSTART:20081101T020000
RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
....

I would like to have it so it is like this:

$data['PRODID'] = -//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN
$data['VERSION'] = 2.0
.......

I did try parse_str but that didn't work. Is there a easy way?

4

2 回答 2

1

编写自己的脚本来解释这一点非常简单。

$lines = explode("\r\n", $string);
$parsed = array();
foreach($lines as $line){
    list($key, $value) = explode(":", $line, 2);
    $parsed[$key] = $value;
}

我立即看到你的脚本将不再有意义的一点,那就是重复的开始键。

为了解决这个问题,您可以按照以下方式做一些事情:

$lines = explode("\n", $string);
$parsed = array();
$current = &$parsed;
foreach($lines as $line){
    list($key, $value) = explode(":", $line, 2);
    if ($key == "BEGIN") {
         $parsed[$value] = array();
         $current = &$parsed[$value];
    } else {
         $current[$key] = $value;
    }
}

这将产生类似的输出

Array
(
    [PRODID] => -//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN
    [VERSION] => 2.0
    [METHOD] => PUBLISH
    [X-CALENDARSERVER-ACCESS] => PUBLIC
    [VTIMEZONE] => Array
        (
            [TZID] => Pacific Time
        )

    [STANDARD] => Array
        (
            [DTSTART] => 20081101T020000
            [RRULE] => FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
        )

)

对于上面的示例(请注意,begin 块之后的所有内容如何根据​​ BEGIN 的值设置为子数组的属性)。

在行动中看到它

对于 iCalendar Parser 的替代实现,您可以看到这个问题

于 2013-08-21T21:20:06.223 回答
0

像这样做?

$string = "...." // all the stuff you have there.

$array = array();

// explode on newlines to go through it line by line
foreach(explode("\n", $string) as $line)
{
    // explode again by ':' and set the key/values
    $tmp = explode(':', $line);
    $array[$tmp[0]] = $tmp[1];
}

请注意,您将覆盖键。(你有两次 BEGIN)。

于 2013-08-21T21:16:33.600 回答