一直都沒有很認真的學習 XML 的使用方式,花了一些時間稍微瞭解了一下 PHP 當中的 SimpleXML、DOM,以及 XML Parser 三種 extensions,各有巧妙不同。但是我的需求算相當低的,所以直接用 SimpleXML 即可達到目地。
簡易讀取 XML 的程式撰寫說明
需要的套件
- /usr/ports/lang/php5
- /usr/ports/textproc/php5-simplexml
- /usr/ports/textproc/php5-xsl
參考文件
- PHP.net SimpleXML Functions
函示使用說明
- 讀取 XML 內容
$xml = new SimpleXMLElement($body);
- 取得屬性
$xml->attributes();
簡單的範例程式
- 程式範例
<?php
$body = '<?xml version="1.0" encoding="UTF-8"?>
<presence xmlns="urn:ietf:params:xml:ns:pidf"
entity="sip:68004810@my.hostname">
<tuple id="68004810" callstatus="0" displayName="68004810" status="1">
<status><basic>open</basic></status>
<contact priority="0">sip:68004810@my.hostname</contact>
<note>Available</note>
</tuple>
</presence>';
$xml = new SimpleXMLElement($body);
print_r ($xml);
print "displayname=" . $xml->tuple->attributes()->displayName . "\n";
print "id=" . $xml->tuple->attributes()->id . "\n";
print "callstatus=" . $xml->tuple->attributes()->callstatus . "\n";
print "status=" . $xml->tuple->status->basic . "\n";
print "contact=" . $xml->tuple->contact . "\n";
print "note=" . $xml->tuple->note . "\n";
?>
- 執行結果
SimpleXMLElement Object
(
[@attributes] => Array
(
[entity] => sip:68004810@my.hostname
)
[tuple] => SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 68004810
[callstatus] => 0
[displayName] => 68004810
[status] => 1
)
[status] => SimpleXMLElement Object
(
[basic] => open
)
[contact] => sip:68004810@my.hostname
[note] => Available
)
)
displayname=68004810
id=68004810
callstatus=0
status=open
contact=sip:68004810@my.hostname
note=Available