header()関数で「Content-type」に「application/xml」を指定します。
header( 'Content-type: application/xml' );
これはすべての出力より先に行う必要があります。さもなくば、「Warning: Cannot modify header information - headers already sent by (output started at C:\localhost\index.php:1)」となり正しく動作しません。
ファイルのエンコーディングがUTF-8の場合には、UTF-8 (BOMなし) に変更します。
| 関数 | 説明 |
|---|---|
| simplexml_import_dom | DOMノードからSimpleXMLElementオブジェクトを取得する |
| simplexml_load_file | XMLファイルをパースし、オブジェクトに代入する |
| simplexml_load_string | XML文字列をオブジェクトに代入する |
例えば次のようなXML文書をSimpleXMLでパースすると、
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
結果は以下のようなオブジェクトとして返されます。
SimpleXMLElement Object
(
[movie] => SimpleXMLElement Object
(
[title] => PHP: Behind the Parser
[characters] => SimpleXMLElement Object
(
[character] => Array
(
[0] => SimpleXMLElement Object
(
[name] => Ms. Coder
[actor] => Onlivia Actora
)
[1] => SimpleXMLElement Object
(
[name] => Mr. Coder
[actor] => El ActÓr
)
)
)
[great-lines] => SimpleXMLElement Object
(
[line] => PHP solves all my web problems
)
[rating] => Array
(
[0] => 7
[1] => 5
)
)
)
名前が同一の要素が複数ある場合には配列としてまとめられるため、これを処理するときにはその点に留意する必要があります。
このオブジェクトが変数$xmlに格納されているとして、XMLの要素や属性にアクセスする方法を次に示します。
| 対象 | コード | 説明 |
|---|---|---|
| <title> | $xml->movie->title |
要素にはオブジェクトのプロパティとしてアクセスする。 |
| <character> |
$xml->movie->characters->character[0]または $xml->movie->characters->character |
同名の要素が複数ある場合には、配列の要素のようにアクセスする。最初の要素へは、それを省いてアクセスできる。 |
| <line> | $xml->movie->{'great-lines'}->line |
PHPの命名規則で使用できない文字を含む名前は、括弧と引用符で囲んで指定する。 |
| <rating type="stars"> | $xml->movie->rating[1]['type'] |
属性には連想配列としてアクセスする。 |
このように取得したXMLの要素や属性は、SimpleXMLElementオブジェクトとなります。よってこれらを文字列として処理するには、(string) としてキャストする必要があります
例えば
<foo data1="a" data2="b" />
のような要素は、
[foo] => SimpleXMLElement Object
(
[@attributes] => Array
(
[data1] => a
[data2] => b
)
)
のように取得できます。この「@attributes」に含まれる要素にアクセスするには、
$xml->foo->attributes()->data1;
とします。
使用方法