首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 產生 Apple Plist 格式資料(XML 與文字格式)

     編輯:PHP 相關知識

PHP 產生 Apple Plist 格式資料(XML 與文字格式)

Plist (Property List) 是 Apple 常用的序列化格式。此 PropertyList 類別可將 PHP 陣列/物件轉換為 Plist XML (v1.0 DTD) 或 OpenStep 文字格式,支援巢狀陣列、關聯陣列、整數、浮點數、字串、布林、Date、Data (Base16/Base64)。

核心類別(精簡版)

<?php
class PropertyList {
    private $obj, $xml, $text;

    public function __construct($obj) { $this->obj = $obj; }

    public function toXml(): string {
        if (isset($this->xml)) return $this->xml;
        $x = new XMLWriter();
        $x->openMemory();
        $x->setIndent(true);
        $x->startDocument('1.0', 'UTF-8');
        $x->writeDTD('plist', '-//Apple//DTD PLIST 1.0//EN', 'https://www.apple.com/DTDs/PropertyList-1.0.dtd');
        $x->startElement('plist');
        $x->writeAttribute('version', '1.0');
        $this->writeXmlValue($x, $this->obj);
        $x->endElement(); // plist
        $x->endDocument();
        $this->xml = $x->outputMemory();
        return $this->xml;
    }

    public function toText(): string {
        if (isset($this->text)) return $this->text;
        $this->text = '';
        $this->writeTextValue($this->text, $this->obj);
        return $this->text;
    }

    // 內部遞歸寫入 XML(略,完整版見原碼)
    // 內部遞歸寫入 Text(略)

    private static function isAssoc(array $arr): bool {
        return array_keys($arr) !== range(0, count($arr)-1);
    }
}

// 便利函式
function plist_encode_xml($obj) { return (new PropertyList($obj))->toXml(); }
function plist_encode_text($obj) { return (new PropertyList($obj))->toText(); }

// 使用範例
$data = [
    'name' => 'AppConfig',
    'version' => 1.2,
    'enabled' => true,
    'items' => ['apple', 'banana'],
    'meta' => (object)['id' => 123, 'tags' => ['ios', 'mac']]
];
header('Content-Type: application/xml; charset=utf-8');
echo plist_encode_xml($data);
?>

支援型別對照表

PHP 型別Plist XML 標籤文字格式
int<integer>數字
float<real>數字
string<string>"字串" (含跳脫)
bool<true/> 或 <false/>YES/NO
關聯陣列<dict><key>k</key><value>...</dict>{ k = v; }
索引陣列<array>...</array>( v, v, )
PlistDate 物件<date>ISO8601</date>"ISO8601"
PlistData 物件<data>Base64</data><Hex>

應用場景

  • iOS/macOS App 設定檔產生(.plist)。
  • API 回應 Plist 格式給舊版客戶端。
  • 資料交換、備份還原。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved