0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Array to XML

Last updated at Posted at 2023-01-10

ググってもXML to Arrayの記事は多いけどArray to XML があんまり少ない気したので。

  • simpleXMLのaddChildメソッドを使いました。
  • 配列の中身をforeachでぶん回しながらノードに子要素を追加してく的な感じで、keyをXML要素名としていきます。
  • 取り出した配列の値が配列の場合は、再帰して、これで多次元配列に対応
    public static function array_to_xml(array $target_array, SimpleXMLElement $xml)
    {
        foreach ($target_array as $key => $value) {
            if(is_array($value)) {
                self::array_to_xml($value, $xml->addChild($key));
            } else {
                $xml->addChild($key, $value);
            }
        }
        return $xml->asXML();
    }

//実行例
//array_to_xml($sample_array, new SimpleXMLElement('<root/>'));
}
  • ※毎回呼び出す時にsimpleXMLのオブジェクト生成して引数に渡す必要があるのはこれちょっとセンスないかなと思うのですが、よしなに
  • 今時jsonでええやんって感じですが
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?