How to parse a .plist file with php?

2019-06-15 04:10发布

Can i parse a plist file with php and kind of get it into an array, like the $_POST[''] so i could call $_POST['body'] and get the string that has the <key> body ?

3条回答
疯言疯语
3楼-- · 2019-06-15 04:46

Took a look at some of the libraries out there but they have external requirements and seem overkill. Here's a function that simply puts the data in to associative arrays. This worked on a couple of exported itunes plist files I tried.

// pass in the full plist file contents
function parse_plist($plist) {
    $result = false;
    $depth = [];
    $key = false;

    $lines = explode("\n", $plist);
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line) {
            if ($line == '<dict>') {
                if ($result) {
                    if ($key) {
                        // adding a new dictionary, the line above this one should've had the key
                        $depth[count($depth) - 1][$key] = [];
                        $depth[] =& $depth[count($depth) - 1][$key];
                        $key = false;
                    } else {
                        // adding a dictionary to an array
                        $depth[] = [];
                    }
                } else {
                    // starting the first dictionary which doesn't have a key
                    $result = [];
                    $depth[] =& $result;
                }

            } else if ($line == '</dict>' || $line == '</array>') {
                array_pop($depth);

            } else if ($line == '<array>') {
                $depth[] = [];

            } else if (preg_match('/^\<key\>(.+)\<\/key\>\<.+\>(.+)\<\/.+\>$/', $line, $matches)) {
                // <key>Major Version</key><integer>1</integer>
                $depth[count($depth) - 1][$matches[1]] = $matches[2];

            } else if (preg_match('/^\<key\>(.+)\<\/key\>\<(true|false)\/\>$/', $line, $matches)) {
                // <key>Show Content Ratings</key><true/>
                $depth[count($depth) - 1][$matches[1]] = ($matches[2] == 'true' ? 1 : 0);

            } else if (preg_match('/^\<key\>(.+)\<\/key\>$/', $line, $matches)) {
                // <key>1917</key>
                $key = $matches[1];
            }
        }
    }
    return $result;
}
查看更多
一夜七次
4楼-- · 2019-06-15 04:47

Googling for "php plist parser" turned up this blog post that seems to be able to do what you are asking for.

查看更多
登录 后发表回答