LoginSignup
10
10

More than 5 years have passed since last update.

PHPでXMLファイルを読み込みで配列変数に格納する方法

Last updated at Posted at 2015-04-08

方法

json_encodeを使うとできます。

$xml_obj = simplexml_load_file('./aaa.xml');
$xml_ary = json_decode(json_encode($xml_obj), true);

注意点

XMLで配列を使用する場合は、要素数が一つの場合は配列が作成されません。

index.php
<?php
function get_xml_ary($xml){
    $xml_obj = simplexml_load_string($xml);
    $xml_ary = json_decode(json_encode($xml_obj), true);
    return $xml_ary;
}
$xml = '<a><b>[0] 1234</b><b>[1] 1234</b></a>';
var_dump(get_xml_ary($xml));

$xml = '<a><b>[0] 1234</b></a>';
var_dump(get_xml_ary($xml));
output
array(1) {
  'b' =>
  array(2) {
    [0] =>
    string(4) "[0] 1234"
    [1] =>
    string(4) "[1] 4567"
  }
}
array(1) {
  'b' =>
  string(4) "[0] 1234"
}

参考

http://fdays.blogspot.jp/2011/03/php-simplexml.html
http://php.net/manual/ja/function.simplexml-load-string.php#102277

10
10
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10