Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class xmldoc {
- function build($name = 'index') {
- $dom = new DOMDocument("1.0");
- $dom->formatOutput = true;
- $root = $dom->createElement($name);
- $dom->appendChild($root);
- return array($root, $dom);
- }
- function add($xmlObject, $parent, $field, $value = false, $textNode = false) {
- $dom = $xmlObject[1];
- $field = $dom->createElement($field);
- $parent->appendChild($field);
- if ($value !== false) {
- $text = ($textNode !== false ? $dom->createTextNode($value) : $dom->createCDATASection($value));
- $field->appendChild($text);
- }
- return $field;
- }
- function attr($xmlObject, $field, $name, $text) {
- $dom = $xmlObject[1];
- $name = $dom->createAttribute($name);
- $field->appendChild($name);
- $value = $dom->createTextNode($text);
- $name->appendChild($value);
- }
- function save($xmlObject, $path, $save = true) {
- $dom = $xmlObject[1];
- echo $dom->saveXML();
- if ($save === true) {
- echo "Wrote to {$path}, " . $dom->save($path) . " bytes.\n" . date('r', time()) . "\n";
- }
- }
- }
- /* Example usage
- $xmlPath = '/path/to/doc/';
- $xmltool = new xmldoc();
- $xmlObject = $xmltool->build('info');
- $root = $xmlObject[0];
- $client = $xmltool->add($xmlObject, $root, 'client');
- $xmltool->add($xmlObject, $client, 'name', 'John');
- $xmltool->add($xmlObject, $client, 'age', 21, true);
- $height = $xmltool->add($xmlObject, $client, 'height', '6.0');
- $xmltool->attr($xmlObject, $height, 'unit', 'feet');
- $xmltool->save($xmlObject, $xmlPath . 'info.xml', false);
- Output:
- <?xml version="1.0"?>
- <info>
- <client>
- <name><![CDATA[John]]></name>
- <age>21</age>
- <height unit="feet"><![CDATA[6.0]]></height>
- </client>
- </info>
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement