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> |