Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Using PHP 4s DOM XML Functions to Create XML Files from SQL Data

By Tony Marston
2005-04-04


Adding optional attributes

It may sometimes be necessary to include additional information for an element with the XML data, and this can be done in the form of attributes. An attribute has a name and a value, and any number of attributes can be added to an element. This must be done by using the '->set_attribute' method immediately after the '->append_child' method and before any '->create_text_node' method, as shown in the following code snippet:

$child = $doc->create_element($fieldname);

$child = $outer->append_child($child);
$child->set_attribute('attr1', 'attrval1');
$child->set_attribute('attr2', 'attrval2');
$value = $doc->create_text_node($fieldvalue);
$value = $child->append_child($value);
These attribute values will then appear within the element's start tag, as follows:

<?xml version="1.0"?>

<root>
<some_table>
<column1 attr1="attrval1" attr2="attrval2">value1</column1>
<column2 attr1="attrval1" attr2="attrval2">value2</column2>
<column3 attr1="attrval1" attr2="attrval2">value3</column3>
</some_table>
</root>
Note that you can insert attributes for row elements as well as column elements.

In my own application I use attribute values to specify the size of each column, so that it does not have to be hard-coded within the XSL file. For multi-line columns I pass values for both 'rows' and 'cols'.

I also use attributes to include any error messages. All error messages get inserted to an array called $errors where the key is the fieldname and the value is the message. The code to insert the error message into the XML document as an attribute of the field which generated the error is as simple as this:

if (isset($errors[$fieldname])) {

$child->set_attribute("error", $errors[$fieldname]);
} // if


Tutorial Pages:
» Intended Audience
» Prerequisites
» Multiple occurrences of a single table
» A One-to-Many relationship
» Adding optional attributes
» Using Multi-Byte Characters
» Conclusion
» References


 | Bookmark
Related Tutorials:
» Zend Framework Tutorial
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1