LoginSignup
1
1

More than 5 years have passed since last update.

DOMDocumentの書き方 : DOCTYPEの記述, createAttribute(), createElement(), appendChild()

Posted at

概要

PHPを使ってiPhoneのiPhone構成ユーティリティを作成する機会があった。
中身はxml形式なので、DOMImplementation()を使ったが、DOCTYEPの追加や要素(ここでは<plist version="1.0"/>の部分)で迷ったため、ここでまとめ。

事前準備

PHPのみ

目的

Doctypeのあるxmlファイルを出力する

ソース

    $filename = 'output.xml';

    $imp = new DOMImplementation();
    # createDocumentType(作成されるドキュメント型の修飾名, 外部サブセットの公開 ID , 外部サブセットのシステム ID )
    $doctype = $imp->createDocumentType('plist', '-//ABC//DTD PLIST 1.0//EN', 'http://www.hogehoge.com/DTDs/PropertyList-1.0.dtd');
    $profile = $imp->createDocument("", "", $doctype);
    $profile->formatOutput = true; # xmlを整形。アウトプットのインデントが揃う
    $profile->version = '1.0';
    $profile->encoding = 'UTF-8';

    $plist_elm = $profile->createElement('plist');
    $plist_attr = $profile->createAttribute('version');
    $plist_attr->value = '1.0';
    $plist_elm->appendChild($plist_attr);
    $profile->appendChild($plist_elm);
    $fuga_elm = $profile->createElement('fuga');
    $profile->appendChild($fuga_elm);
    $fugafuga_elm = $profile->createElement('fugafuga', 'foo');
    $fuga_elm->appendChild($fugafuga_elm);

    $profile->save($filename); # xmlファイル形式に出力

    print "output complete ! "; # 終了通知

出力結果

output.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//ABC//DTD PLIST 1.0//EN" "http://www.hogehoge.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"/>
<fuga>
  <fugafuga>foo</fugafuga>
</fuga>
1
1
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
1
1