simplexml_load_file simplexml_load_string
simplexml_load_fileで、ちょっとん?だったのでメモ。ZFのissueに上がっていたのですが、今は見失ってしまいました・・クローズしたのかもしれない。
ほぼ同じ構造のドキュメントですがZend_Config化すると$config->files->file->id等で値を取得しようとしても、1要素の場合は取得できるが、2要素以上あると、取得できなくなってしまう。
たぶん、構造の定義段階ではっきりしておくべきなんでしょうけど・・XMLを配列に変換する際のルール的には数値添字かどうかで識別するしかないのかもしれません。Zend_Config_Iniなら配列か値かは確実に識別できるんですけど・・・
<?xml version="1.0" encoding="UTF-8"?> <root> <files> <file id="index" location="index.html" /> </files> </root>
<?xml version="1.0" encoding="UTF-8"?> <root> <files> <file id="index" location="index.html" /> <file id="admin" location="admin.html" /> </files> </root>
これら、ほぼ似た構造のXML文書に対して、simplexml_load_file等で読み込むと、
<?php $test0 = <<<EOL <?xml version="1.0" encoding="UTF-8"?> <root> <files> <file id="index" location="index.html" /> </files> </root> EOL; $testXml0 = simplexml_load_string($test0); var_dump($testXml0); $test1 = <<<EOL <?xml version="1.0" encoding="UTF-8"?> <root> <files> <file id="index" location="index.html" /> <file id="admin" location="admin.html" /> </files> </root> EOL; $testXml1 = simplexml_load_string($test1); var_dump($testXml1); //結果 object(SimpleXMLElement)#1 (1) { ["files"]=> object(SimpleXMLElement)#2 (1) { ["file"]=> object(SimpleXMLElement)#3 (1) { ["@attributes"]=> array(2) { ["id"]=> string(5) "index" ["location"]=> string(10) "index.html" } } } } object(SimpleXMLElement)#4 (1) { ["files"]=> object(SimpleXMLElement)#5 (1) { ["file"]=> array(2) { [0]=> object(SimpleXMLElement)#6 (1) { ["@attributes"]=> array(2) { ["id"]=> string(5) "index" ["location"]=> string(10) "index.html" } } [1]=> object(SimpleXMLElement)#7 (1) { ["@attributes"]=> array(2) { ["id"]=> string(5) "admin" ["location"]=> string(10) "admin.html" } } } } }
このとき、構造的にはほぼ一緒なのだけれど、要素数が1か2以上かによって、file要素の型が変わってしまいます。
うーん、そういうもの?なんか、うまい方法があるんでしょうか。。1要素の場合でもリストとして扱うような書き方を検討する必要があるのかもしれません。