How to parse a .plist file with php?
Asked Answered
P

3

13

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 ?

Pedant answered 17/11, 2009 at 15:22 Comment(0)
G
1

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

Gallipot answered 17/11, 2009 at 15:31 Comment(1)
The linked blog no longer exists.Cuboid
S
0

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;
}
Scoundrelly answered 12/2, 2016 at 21:32 Comment(3)
I... is this using regular expressions to try and parse XML?Burgess
xml parsers put the key/value of the plist entry as separate entities in the track. this puts them as key value attributed arrays. /shrugScoundrelly
You're relying on there being new lines and specifically formed xml tags.Burgess

© 2022 - 2024 — McMap. All rights reserved.