PHP simplexml_load_string()関数
例
XML文字列をオブジェクトに変換してから、オブジェクトのキーと要素を出力します。
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
print_r($xml);
?>
定義と使用法
simplexml_load_string()関数は、整形式のXML文字列をオブジェクトに変換します。
構文
simplexml_load_string(data, class, options, ns, is_prefix)
パラメータ値
Parameter | Description |
---|---|
data | Required. Specifies a well-formed XML string |
class | Optional. Specifies the class of the new object |
options | Optional. Specifies additional Libxml parameters. Is set by specifying the option and 1 or 0 (TRUE or FALSE, e.g. LIBXML_NOBLANKS(1)) Possible values:
|
ns | Optional. Specifies a namespace prefix or URI |
is_prefix | Optional. Specifies a Boolean value. TRUE if ns is a prefix. FALSE if ns is a URI. Default is FALSE |
技術的な詳細
戻り値: | 成功した場合のSimpleXMLElementオブジェクト。失敗するとFALSE |
---|---|
PHPバージョン: | 5歳以上 |
その他の例
例
XML文字列の各要素からデータを出力します。
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>
例
各子ノードの要素の名前とデータをXML文字列で出力します。
<?php
$note=<<<XML
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Do not forget me this weekend!</body>
</note>
XML;
$xml=simplexml_load_string($note);
echo $xml->getName() . "<br>";
foreach($xml->children() as $child)
{
echo $child->getName() . ": " . $child . "<br>";
}
?>
❮PHPSimpleXMLリファレンス