【问题标题】:How to parse a .plist file with php?如何用 php 解析 .plist 文件?
【发布时间】:2010-12-17 12:02:43
【问题描述】:

我可以用 php 解析一个 plist 文件并将其放入一个数组中,比如$_POST[''],这样我就可以调用$_POST['body'] 并获取具有<key> body 的字符串吗?

【问题讨论】:

    标签: php arrays post parsing plist


    【解决方案1】:

    查看了那里的一些库,但它们有外部要求并且看起来有点矫枉过正。这是一个简单地将数据放入关联数组的函数。这适用于我尝试的几个导出的 iTunes plist 文件。

    // 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;
    }
    

    【讨论】:

    • 我...这是用正则表达式来尝试解析XML吗?
    • xml 解析器将 plist 条目的键/值作为单独的实体放在轨道中。这将它们作为键值属性数组。 /耸肩
    • 您依赖的是新行和专门形成的 xml 标签。
    【解决方案2】:
    【解决方案3】:

    谷歌搜索“php plist parser”出现了this 博客文章,似乎能够满足您的要求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      相关资源
      最近更新 更多