PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<scandirDomAttribute->name>
view the version of this page
Last updated: Thu, 21 Aug 2003

XXIV. DOM XML functions

Introduction

Warning

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

The DOM XML extension has been overhauled in PHP 4.3.0 to better comply with the DOM standard. The extension still contains many old functions, but they should no longer be used. In particular, functions that are not object-oriented should be avoided.

The extension allows you to operate on an XML document with the DOM API. It also provides a function domxml_xmltree() to turn the complete XML document into a tree of PHP objects. Currently, this tree should be considered read-only — you can modify it, but this would not make any sense since DomDocument_dump_mem() cannot be applied to it. Therefore, if you want to read an XML file and write a modified version, use DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), etc. and finally the DomDocument_dump_mem() function.

Requirements

This extension makes use of the GNOME XML library. Download and install this library. You will need at least libxml-2.4.14. To use DOM XSLT features you can use the libxslt library and EXSLT enhancements from http://www.exslt.org/. Download and install these libraries if you plan to use (enhanced) XSLT features. You will need at least libxslt-1.0.18.

Installation

This extension is only available if PHP was configured with --with-dom[=DIR]. Add --with-dom-xslt[=DIR] to include DOM XSLT support. DIR is the libxslt install directory. Add --with-dom-exslt[=DIR] to include DOM EXSLT support, where DIR is the libexslt install directory.

Note to Win32 Users: In order to enable this module on a Windows environment, you must copy one additional file from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your Windows machine (Ex: C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). For PHP <= 4.2.0 copy libxml2.dll, for PHP >= 4.3.0 copy iconv.dll from the DLL folder to your SYSTEM32 folder.

Deprecated functions

There are quite a few functions that do not fit into the DOM standard and should no longer be used. These functions are listed in the following table. The function DomNode_append_child() has changed its behaviour. It now adds a child and not a sibling. If this breaks your application, use the non-DOM function DomNode_append_sibling().

Table 1. Deprecated functions and their replacements

Old functionNew function
xmldocdomxml_open_mem()
xmldocfiledomxml_open_file()
domxml_new_xmldocdomxml_new_doc()
domxml_dump_memDomDocument_dump_mem()
domxml_dump_mem_fileDomDocument_dump_file()
DomDocument_dump_mem_fileDomDocument_dump_file()
DomDocument_add_rootDomDocument_create_element() followed by DomNode_append_child()
DomDocument_dtdDomDocument_doctype()
DomDocument_rootDomDocument_document_element()
DomDocument_childrenDomNode_child_nodes()
DomDocument_imported_nodeNo replacement.
DomNode_add_childCreate a new node with e.g. DomDocument_create_element() und add it with DomNode_append_child().
DomNode_childrenDomNode_child_nodes()
DomNode_parentDomNode_parent_node()
DomNode_new_childCreate a new node with e.g. DomDocument_create_element() and add it with DomNode_append_child().
DomNode_set_contentCreate a new node with e.g. DomDocument_create_text_node() and add it with DomNode_append_child().
DomNode_get_contentContent is just a text node and can be accessed with DomNode_child_nodes().
DomNode_set_contentContent is just a text node and can be added with DomNode_append_child().

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Table 2. XML constants

ConstantValueDescription
XML_ELEMENT_NODE (integer) 1Node is an element
XML_ATTRIBUTE_NODE (integer) 2Node is an attribute
XML_TEXT_NODE (integer) 3Node is a piece of text
XML_CDATA_SECTION_NODE (integer) 4 
XML_ENTITY_REF_NODE (integer) 5 
XML_ENTITY_NODE (integer) 6Node is an entity like &nbsp;
XML_PI_NODE (integer) 7Node is a processing instruction
XML_COMMENT_NODE (integer) 8Node is a comment
XML_DOCUMENT_NODE (integer) 9Node is a document
XML_DOCUMENT_TYPE_NODE (integer) 10 
XML_DOCUMENT_FRAG_NODE (integer) 11 
XML_NOTATION_NODE (integer) 12 
XML_GLOBAL_NAMESPACE (integer) 1 
XML_LOCAL_NAMESPACE (integer) 2 
XML_HTML_DOCUMENT_NODE (integer)   
XML_DTD_NODE (integer)   
XML_ELEMENT_DECL_NODE (integer)   
XML_ATTRIBUTE_DECL_NODE (integer)   
XML_ENTITY_DECL_NODE (integer)   
XML_NAMESPACE_DECL_NODE (integer)   
XML_ATTRIBUTE_CDATA (integer)   
XML_ATTRIBUTE_ID (integer)   
XML_ATTRIBUTE_IDREF (integer)   
XML_ATTRIBUTE_IDREFS (integer)   
XML_ATTRIBUTE_ENTITY (integer)   
XML_ATTRIBUTE_NMTOKEN (integer)   
XML_ATTRIBUTE_NMTOKENS (integer)   
XML_ATTRIBUTE_ENUMERATION (integer)   
XML_ATTRIBUTE_NOTATION (integer)   
XPATH_UNDEFINED (integer)   
XPATH_NODESET (integer)   
XPATH_BOOLEAN (integer)   
XPATH_NUMBER (integer)   
XPATH_STRING (integer)   
XPATH_POINT (integer)   
XPATH_RANGE (integer)   
XPATH_LOCATIONSET (integer)   
XPATH_USERS (integer)   
XPATH_NUMBER (integer)   

Classes

The API of the module follows the DOM Level 2 standard as closely as possible. Consequently, the API is fully object-oriented. It is a good idea to have the DOM standard available when using this module. Though the API is object-oriented, there are many functions which can be called in a non-object-oriented way by passing the object to operate on as the first argument. These functions are mainly to retain compatibilty to older versions of the extension, and should not be used when creating new scripts.

This API differs from the official DOM API in two ways. First, all class attributes are implemented as functions with the same name. Secondly, the function names follow the PHP naming convention. This means that a DOM function lastChild() will be written as last_child().

This module defines a number of classes, which are listed — including their method — in the following tables. Classes with an equivalent in the DOM standard are named DOMxxx.

Table 3. List of classes

Class nameParent classes
DomAttributeDomNode
DomCDataDomNode
DomCommentDomCData : DomNode
DomDocumentDomNode
DomDocumentTypeDomNode
DomElementDomNode
DomEntityDomNode
DomEntityReferenceDomNode
DomProcessingInstructionDomNode
DomTextDomCData : DomNode
ParserCurrently still called DomParser
XPathContext 

Table 4. DomDocument class (DomDocument : DomNode)

Method nameFunction nameRemark
doctypeDomDocument_doctype() 
document_elemnentDomDocument_document_element() 
create_elementDomDocument_create_element() 
create_text_nodeDomDocument_create_text_node() 
create_commentDomDocument_create_comment() 
create_cdata_sectionDomDocument_create_cdata_section() 
create_processing_instructionDomDocument_create_processing_instruction() 
create_attributeDomDocument_create_attribute() 
create_entity_referenceDomDocument_create_entity_reference() 
get_elements_by_tagnameDomDocument_get_elements_by_tagname() 
get_element_by_idDomDocument_get_element_by_id() 
dump_memDomDocument_dump_mem()not DOM standard
dump_fileDomDocument_dump_file()not DOM standard
html_dump_memDomDocument_html_dump_mem()not DOM standard
xpath_initxpath_initnot DOM standard
xpath_new_contextxpath_new_contextnot DOM standard
xptr_new_contextxptr_new_contextnot DOM standard

Table 5. DomElement class (DomElement : DomNode)

Method nameFunction nameRemark
tagnameDomElement_tagname() 
get_attributeDomElement_get_attribute() 
set_attributeDomElement_set_attribute() 
remove_attributeDomElement_remove_attribute() 
get_attribute_nodeDomElement_get_attribute_node() 
get_elements_by_tagnameDomElement_get_elements_by_tagname() 
has_attributeDomElement_has_attribute() 

Table 6. DomNode class

Method nameRemark
DomNode_node_name() 
DomNode_node_value() 
DomNode_node_type() 
DomNode_last_child() 
DomNode_first_child() 
DomNode_child_nodes() 
DomNode_previous_sibling() 
DomNode_next_sibling() 
DomNode_parent_node() 
DomNode_owner_document() 
DomNode_insert_before() 
DomNode_append_child() 
DomNode_append_sibling()Not in DOM standard. This function emulates the former behaviour of DomNode_append_child().
DomNode_remove_child() 
DomNode_has_child_nodes() 
DomNode_has_attributes() 
DomNode_clone_node() 
DomNode_attributes() 
DomNode_unlink_node()Not in DOM standard
DomNode_replace_node()Not in DOM standard
DomNode_set_content()Not in DOM standard, deprecated
DomNode_get_content()Not in DOM standard, deprecated
DomNode_dump_node()Not in DOM standard
DomNode_is_blank_node()Not in DOM standard

Table 7. DomAttribute class (DomAttribute : DomNode)

Method name Remark
nameDomAttribute_name() 
valueDomAttribute_value() 
specifiedDomAttribute_specified() 

Table 8. DomProcessingInstruction class (DomProcessingInstruction : DomNode)

Method nameFunction nameRemark
targetDomProcessingInstruction_target() 
dataDomProcessingInstruction_data() 

Table 9. Parser class

Method nameFunction nameRemark
add_chunkParser_add_chunk() 
endParser_end() 

Table 10. XPathContext class

Method nameFunction nameRemark
evalXPathContext_eval() 
eval_expressionXPathContext_eval_expression() 
register_nsXPathContext_register_ns() 

Table 11. DomDocumentType class (DomDocumentType : DomNode)

Method nameFunction nameRemark
nameDomDocumentType_name() 
entitiesDomDocumentType_entities() 
notationsDomDocumentType_notations() 
public_idDomDocumentType_public_id() 
system_idDomDocumentType_system_id() 
internal_subsetDomDocumentType_internal_subset() 

The classes DomDtd is derived from DomNode. DomComment is derived from DomCData.

Examples

Many examples in this reference require an XML string. Instead of repeating this string in every example, it will be put into a file which will be included by each example. This include file is shown in the following example section. Alternatively, you could create an XML document and read it with DomDocument_open_file().

Example 1. Include file example.inc with XML string

<?php
$xmlstr = "<?xml version='1.0' standalone='yes'?>
<!DOCTYPE chapter SYSTEM '/share/sgml/Norman_Walsh/db3xml10/db3xml10.dtd'
[ <!ENTITY sp \"spanish\">
]>
<!-- lsfj  -->
<chapter language='en'><title language='en'>Title</title>
 <para language='ge'>
  &amp;sp;
  <!-- comment -->
  <informaltable ID='findme' language='&amp;sp;'>
   <tgroup cols='3'>
    <tbody>
     <row><entry>a1</entry><entry
morerows='1'>b1</entry><entry>c1</entry></row>
<row><entry>a2</entry><entry>c2</entry></row>
     <row><entry>a3</entry><entry>b3</entry><entry>c3</entry></row>
    </tbody>
   </tgroup>
  </informaltable>
 </para>
</chapter>";
?>

Table of Contents
DomAttribute->name --  Returns name of attribute
DomAttribute->specified --  Checks if attribute is specified
DomAttribute->value --  Returns value of attribute
DomDocument->add_root [deprecated] --  Adds a root node
DomDocument->create_attribute -- Create new attribute
DomDocument->create_cdata_section -- Create new cdata node
DomDocument->create_comment -- Create new comment node
DomDocument->create_element_ns --  Create new element node with an associated namespace
DomDocument->create_element -- Create new element node
DomDocument->create_entity_reference -- 
DomDocument->create_processing_instruction -- Creates new PI node
DomDocument->create_text_node -- Create new text node
DomDocument->doctype --  Returns the document type
DomDocument->document_element --  Returns root element node
DomDocument->dump_file --  Dumps the internal XML tree back into a file
DomDocument->dump_mem --  Dumps the internal XML tree back into a string
DomDocument->get_element_by_id --  Searches for an element with a certain id
DomDocument->get_elements_by_tagname -- 
DomDocument->html_dump_mem --  Dumps the internal XML tree back into a string as HTML
DomDocument->xinclude --  Substitutes XIncludes in a DomDocument Object.
DomDocumentType->entities --  Returns list of entities
DomDocumentType->internal_subset --  Returns internal subset
DomDocumentType->name --  Returns name of document type
DomDocumentType->notations --  Returns list of notations
DomDocumentType->public_id --  Returns public id of document type
DomDocumentType->system_id --  Returns system id of document type
DomElement->get_attribute_node --  Returns value of attribute
DomElement->get_attribute --  Returns value of attribute
DomElement->get_elements_by_tagname --  Gets elements by tagname
DomElement->has_attribute --  Checks to see if attribute exists
DomElement->remove_attribute --  Removes attribute
DomElement->set_attribute --  Adds new attribute
DomElement->tagname --  Returns name of element
DomNode->add_namespace --  Adds a namespace declaration to a node.
DomNode->append_child --  Adds new child at the end of the children
DomNode->append_sibling --  Adds new sibling to a node
DomNode->attributes --  Returns list of attributes
DomNode->child_nodes --  Returns children of node
DomNode->clone_node --  Clones a node
DomNode->dump_node --  Dumps a single node
DomNode->first_child --  Returns first child of node
DomNode->get_content --  Gets content of node
DomNode->has_attributes --  Checks if node has attributes
DomNode->has_child_nodes --  Checks if node has children
DomNode->insert_before --  Inserts new node as child
DomNode->is_blank_node --  Checks if node is blank
DomNode->last_child --  Returns last child of node
DomNode->next_sibling --  Returns the next sibling of node
DomNode->node_name --  Returns name of node
DomNode->node_type --  Returns type of node
DomNode->node_value --  Returns value of a node
DomNode->owner_document --  Returns the document this node belongs to
DomNode->parent_node --  Returns the parent of the node
DomNode->prefix --  Returns name space prefix of node
DomNode->previous_sibling --  Returns the previous sibling of node
DomNode->remove_child --  Removes child from list of children
DomNode->replace_child --  Replaces a child
DomNode->replace_node --  Replaces node
DomNode->set_content --  Sets content of node
DomNode->set_name --  Sets name of node
DomNode->set_namespace --  Sets namespace of a node.
DomNode->unlink_node --  Deletes node
DomProcessingInstruction->data --  Returns data of pi node
DomProcessingInstruction->target --  Returns target of pi node
DomXsltStylesheet->process --  Applies the XSLT-Transformation on a DomDocument Object.
DomXsltStylesheet->result_dump_file --  Dumps the result from a XSLT-Transformation into a file
DomXsltStylesheet->result_dump_mem --  Dumps the result from a XSLT-Transformation back into a string
domxml_new_doc --  Creates new empty XML document
domxml_open_file -- Creates a DOM object from XML file
domxml_open_mem -- Creates a DOM object of an XML document
domxml_version --  Get XML library version
domxml_xmltree --  Creates a tree of PHP objects from an XML document
domxml_xslt_stylesheet_doc --  Creates a DomXsltStylesheet Object from a DomDocument Object.
domxml_xslt_stylesheet_file --  Creates a DomXsltStylesheet Object from a xsl document in a file.
domxml_xslt_stylesheet --  Creates a DomXsltStylesheet Object from a xml document in a string.
xpath_eval_expression --  Evaluates the XPath Location Path in the given string
xpath_eval --  Evaluates the XPath Location Path in the given string
xpath_new_context --  Creates new xpath context
xptr_eval --  Evaluate the XPtr Location Path in the given string
xptr_new_context --  Create new XPath Context


add a note add a note User Contributed Notes
DOM XML functions
pookey at pookey dot co dot uk
08-Oct-2003 05:41
LDAP to XML script - http://www.pookey.co.uk

<?php

$ldapServer 
'localhost';
$ldapBase 'DC=anlx,DC=net';

/*
* try to connect to the server
*/
$ldapConn ldap_connect($ldapServer);
if (!
$ldapConn)
{
  die(
'Cannot Connect to LDAP server');
}

/*
* bind anonymously
*/
$ldapBind ldap_bind($ldapConn);
if (!
$ldapBind)
{
  die(
'Cannot Bind to LDAP server');
}

/*
* set the ldap options
*/
ldap_set_option($ldapConnLDAP_OPT_PROTOCOL_VERSION3);

/*
* search the LDAP server
*/
$ldapSearch ldap_search($ldapConn$ldapBase"(cn=*)");
$ldapResults ldap_get_entries($ldapConn$ldapSearch);

header('Content-type: text/xml');
$xmlRoot domxml_new_doc("1.0");
$xmlContacts $xmlRoot->create_element('contacts');
$xmlRoot->append_child($xmlContacts);

for (
$item 0$item $ldapResults['count']; $item++)
{
 
$xmlContact $xmlRoot->create_element("contact");
  for (
$attribute 0$attribute $ldapResults[$item]['count']; $attribute++)
  {
   
$data $ldapResults[$item][$attribute];
   
$xmlValues $xmlRoot->create_element($data 's');
    for (
$value 0$value $ldapResults[$item][$data]['count']; $value++)
    {
     
$xmlValue $xmlRoot->create_element($data);
     
$xmlValueText $xmlRoot->create_text_node($ldapResults[$item][$data][$value]);
     
$xmlValue->append_child($xmlValueText);
     
$xmlValues->append_child($xmlValue);
    }
   
$xmlContact->append_child($xmlValues);
  }
 
$xmlContacts->append_child($xmlContact);
}

echo 
$xmlRoot->dump_mem();
?>
call me a friend.
25-Sep-2003 05:13
I had a lot of trouble getting this thing to compile on a Solaris 8 box. Here's what I learned:

**as of this writing, the pre-compiled binaries available from http://garypennington.net/libxml2/ are not recent enough. You'll need to compile the source binaries available on the FTP site mentioned on http://xmlsoft.org/XSLT/downloads.html

**you need to have zlib installed, and add the "--with-zlib-dir=[dir]" when you ./configure php

**you may or may not need to use gnu's make instead of the standard Sun make

**if your 'make' bombs out, and you had had a few aborted ./configure's, you need to run a 'make clean'

hope this helps
php at theovis dot com
24-Jul-2003 08:15
<?php
/*
// I tried to get some functionality out of the the dom_xml functions (it's my first dom_xml script)
// i created a little script to parse or to add/edit a xml file.
// It's probabaly not the most efficient but it seams to work
//
// It 's based on a (HR) xml file, and xsl file - you can get them here http://theovis.com/sample
//
// Used win32 - apache 1.3.26 - php 4.3.0 - Theo Vis php@theovis.com
// You are free to e-mail if you have comment on the code

// PS. Change the path your XML-FILES

///
// Default var - Standaard Variabelen
///

// Path is necessary to use domxml_open_file function
// In tried to use file_get_contents but it didn't seams to work
 
*/
$path "C:/PATH/";
// Get file name from url input - Variabelen ophalen
$xmldoc $_REQUEST['xmldoc'];
$xsldoc $_REQUEST['xsldoc'];
$add $_REQUEST['add'];
$edit $_REQUEST['edit'];
// New-file
$xmlnieuw $path."sample_personalia-new.xml";
// Start script
if (!$xmldoc){
   
// Set default xml-file - if there is nog xmldoc set
   
$xmldoc "sample_personalia.xml";
//    $xsldoc = "sample_personalia.xsl"; // View
   
$xsldoc "edit_personalia.xsl"
}

$xmlfile $path.$xmldoc;
$xslfile $path.$xsldoc;

// Open XML - File
$dom domxml_open_file($xmlfile);   

////
// Edit (replace content)
////

if($edit){

   
// Walk trough the post vars (all elements within the form)
    // Alle elementen doorlopen die gepost worden

   
while (list ($tagname$tagcontent) = each ($_POST)) {
   
       
// Count how many childs there are
        // Tellen hoeveel kinderen er zijn (for-each elementen)

       
for($i=0;$i count($tagcontent);$i++){
           
$h $i+1;
           
           
// Get content
            // Content ophalen
           
$content $tagcontent[$h];

           
// Get the elements
           
$elements $dom->get_elements_by_tagname($tagname);

           
// Replace the content (first use have to set the element, else it would be added instead of replace
            // De inhoud vervangen
           
$element $elements[$i];
           
$child $element->first_child();
           
$child->set_content($content);
        }
    }

   
// Store the new content into a new-file
   
$result $dom ->dump_file($xmlnieuw);
}

////
// Add (Add node (value (not attribute)
////

if ($add){

   
// To add a node (it's working, but the code it's  buddy)
    // It's first add's a parant then i will look for child node's
    // It's working buttom up

   
$elements $dom->get_elements_by_tagname($newelement);
   
$element $elements[0];
   
   
// Get the parant
   
$parent $element->parent_node();
   
$parent_name $parent-> node_name();
   
$parent_elements $dom->get_elements_by_tagname($parent_name);
   
$parent_element=$parent_elements[0];
       
   
// Get the grand parant
   
$grand_parent $parent_element -> parent_node();
   
$grand_parent_name $grand_parent -> node_name();

   
// Create Parent
   
$createparentnode $dom -> create_element($parent_name);
   
$grand_parent -> append_child($createparentnode);

   
// Create child nodes
   
$parent_elements $dom->get_elements_by_tagname($parent_name);
   
$countparents count($parent_elements);
   
$parent_element $parent_elements[0];

   
// The last element is the new element
   
$new_parant $countparents 1;

   
// Set new parant
   
$new_parent_element $parent_elements[$new_parant];
   
$childnodes $parent_element -> child_nodes();
   
$aantal count($childnodes);
    for(
$i=0;$i count($childnodes);$i++){
       
$child $childnodes[$i];
       
$child_name $child -> node_name();
       
$type $child ->node_type();
        if (
$type == 1){ // Not a text node
           
$createchildnode $dom -> create_element($child_name);
           
$new_parent_element-> append_child($createchildnode);
        }
       
//$createchildnode -> set_attribute("","");
   
}

   
$result $dom ->dump_file($xmlnieuw);
}

////
// Display
////

// Add the xls-file to a parameter
$xslt_parameters[xsldocu] = $xsldoc;
$xslt_parameters[xmldocu] = $xmldoc;

// XSL Doc inladen - XML Document is all ready loaded
$xsldoc domxml_xslt_stylesheet_file($xslfile);

// XML en XLS processen
$result $xsldoc->process($dom,$xslt_parameters);
print 
$xsldoc->result_dump_mem($result);     

?>
nospam at phppatterns dot com
10-Apr-2003 03:51
If you're having trouble understanding how the the DOM XML extension fits together you may find the UML diagram here helps: http://www.phppatterns.com/index.php/article/articleview/38
pbougrier at micropole-univers dot com
05-Apr-2003 05:17
If you use another encoding than UTF-8, the API seems to bug with conversion errors. Forget it, just follow the rules, for example with ISO-8859-1 encoding :

// you can't specify an encoding with domxml_new_doc(),
// so do it with domxml_open_mem() or domxml_open_file()
$dom = domxml_open_mem('<?xml version="1.0" encoding="ISO-8859-1"?><d嶴?vu/>');

// to have a clean DOM doc, remove the root node with :
$dom->remove_child($dom->document_element());

// now put my ISO-8859-1 element :
$elt = $dom->create_element(utf8_encode("a_new_d嶴?vu"));
$dom->append_child($elt);

// ... and read it :
echo utf8_decode($elt->node_name());

// the dump works fine :
echo $dom->dump_mem();

more details on http://xmlsoft.org/encoding.html
sorn at dsl dot upc dot es
18-Mar-2003 07:38
When parsing "iso-8859-1" encoded XML files, use "utf8_decode" to recover node contents (libxml uses "UTF-8" internal encoding, so conversion needed).

--- BEGIN: mydata.xml ---
<?xml version="1.0" encoding="iso-8859-1"?>
...
--- END: mydata.xml---

--- BEGIN: myparser.php ---
<?php
...
$domxml domxml_open_file("mydata.xml"));
...
$content utf8_decode(trim($node->content));
echo 
$content;
...
?>
--- END: myparser.php

-eof-
dgraf at mail dot ru
02-Mar-2003 11:07
Hi !

Jus wanted to inform the community that if one searches for latest libxml/libxslt windows biniaries these link is the new location of windows port maintainer

http://www.zlatkovic.com/projects/libxml/index.html

Luck !
02-Feb-2003 08:12
When working with DOM, be sure that you look at the DOM Interface Specification.  The level 2 core specification is loated at the link below:

http://www.w3.org/TR/DOM-Level-2-Core/core.html

Remember that the object hierarchy defined here is implemented also in PHP.

As a result, all Documents are Elements, and all Elements are Nodes.  You do not need to convert from elements to nodes before you add them to other elements.

Example:

<?php
/**

  domtest.php: Proof of Concept for DOM XML
  PHP version: 4.3.0
  libxml-2.5.1
   
Your "View Source" from your browser should look like:

<?xml version="1.0"?>
<html><body><h1>Hello, how are you?</h1></body></html>

*/

// Create a new DomAttribute object
$dom domxml_new_doc('1.0');

// Create elements
$htmlElement $dom->create_element('html');
$bodyElement $dom->create_element('body');
$headingElement $dom->create_element('h1');
$headingTextElement $dom->create_text_node("Hello, how are you?");

// Construct the XML document
$headingElement->add_child($headingTextElement);
$bodyElement->add_child($headingElement);
$htmlElement->add_child($bodyElement);

// Add the root element to the document
$dom->append_child($htmlElement);

// Output the document to the browser
echo $dom->dump_mem();

?>
veebeesix at yahoo dot com
28-Nov-2002 01:58
Set your php.ini file to have always_load_raw_form_data set to be true.  You want to use $HTTP_RAW_FORM_DATA to read the XML POST, otherwise php will break it into name value pairs.  You can try to glue these name/value pairs back together, but the former is much easier.
HTH, Mike
veebeesix at yahoo dot com
28-Nov-2002 01:41
Couple of features of PHP probably at work.  If the JavaScript object that you are sending sends a Content Type header that is recognized by PHP (probably "text/xml") it's default behavior (believe it or not) is to parse the XML doc into name/value pairs.  The easiest way around this is to change the default behavior in php.ini with the setting "always_load_http_raw_post_data" (it's something to that effect).  You can then reference $HTTP_RAW_POST_DATA which is not broken into name/value pairs.  If the setting is not set in php.ini, the only time that PHP will set the raw post array is if the content type is set to something with which it is not familiar (e.g., "text/weirdstuff").

After  reading in the XML doc, you can easily use the domxml or regular SAX functions to operate on it.

Hope this helps, Mike
krator at krator dot com
05-Nov-2002 11:51
If you are using php on windows then install MSXML Core Services and use their tools.  This can be done by using the php COM functions.

<?php
$xmlparser 
= new COM("Microsoft.XMLDOM") or die("Unable to instanciate MSXML");
echo 
"Loaded MSXML.\n";
$xmlparser->async="false";
$xmlparser->validateOnParse="true";
$xmlparser->load("d:\\xmldata\\test.xml");

echo 
"Error Code: ";
echo 
$xmlparser->parseError->errorCode;
echo 
"Error Reason: ";
echo 
$xmlparser->parseError->reason;
echo 
"Error Line: ";
echo 
$xmlparser->parseError->line;
?>
chiefgeek (at) ecodedesign.com
26-Jul-2002 07:13
With the release of PHP 4.2.0 exslt integration in the domxml extension was added.  This can be configured using
./configure --with-dom-exslt[=DIR] (and --with-dom-xslt) as can be seen in the changelog.

The set of classes and methods that have been added are undocumented.  After scouring the search engines I still came up with nothing...so I did a little digging on my own.  This is what I have found so far.  I'll just list new functions and classes then give some examples.

There are 5 new functions added: (I don't know all the paremeters yet, but this is what i do know)

FUNCTIONS:
=> domxml_xslt_version
=> domxml_xslt_stylesheet
=> domxml_xslt_stylesheet_doc
=> domxml_xslt_stylesheet_file
=> domxml_xslt_process

Function explanations:
=> domxml_xslt_version() - Have a guess what this does.  Hint it returns a string.

=> domxml_xslt_stylesheet - expects only 1 parameter, a string representation of an XSLT document.   Returns an object of class XsltStylesheet

=> domxml_xslt_stylesheet_doc - not sure about this one yet, it takes just one parameter, an object.  What kind?  Beats me.

=> domxml_xslt_stylesheet_file - just 1 parameter,  the filename (as a string) of an XSLT doc.  Returns an object of class XsltStylesheet

=> domxml_xslt_process (?) still working on this one..

NEW CLASSES, as far as i can tell:

Class Name:
XsltStylesheet

Methods:
=>process

=> process - as far as I can tell this method takes in a DomDocument representation of an XML file and returns a translated DomDocument.

Now for an example:
(Assume person.xml is a properly fomatted XML document.  Same goes for person.xsl.)

<?php

// Create a DOM representation of the xsl file
$xsltdom domxml_xslt_stylesheet_file("person.xsl");

// Create a DOM representation of the xml file
$xmldom domxml_open_file("person.xml");

//Now for the magic
$result $xsltdom->process($xmldom);

// Finally dump the contents to the browser
echo $result->html_dump_mem();

/**
 * Note $result is an object of class DomDocument and so many
 * methods can be used to modify and dump it to the browser.
 *
 * In actual fact $result is an XML representation of an HTML document
 */
?>
steve at stevedix dot de
03-Jul-2002 10:54
Note that attempting to compile both the DOMXML and XMLRPC libraries

(--with-dom and --with-xmlrpc)

into php will cause linking errors.
nlaine at filfog dot com
14-May-2002 08:52
Regarding the notes from
madsosterby@mail1.stofanet.dk
23-Nov-2001 06:27

here is a complement for win32

to make it very simple: php as an apache module

php.ini

extension_dir = c:\php\sapi

uncomment this line
extension=php_domxml.dll

drag and drop the php_domxml.dll which is originally in c:\php\extensions into c:\php\sapi

you're done DOM is activated

(nb same way to load the sablotron module except that you have to copy these files which are originally inside c:\php\dlls

sablot.dll
expat.dll
iconv.dll

into c:\winnt\system32)

two other things:

domxml_open_file() seems to require an absolute path starting at c:\....
however you can fread/file your xml file before and then use domxml_open_mem()

it is a good idea to validate your file before you try and parse it !!

some urls to validate your xml:

http://www.stg.brown.edu/service/xmlvalid/
http://www.cogsci.ed.ac.uk/%7Erichard/xml-check.html

enjoy urself !
ncik
sbarnum at pointsystems com
16-Mar-2002 06:37
Here's a nice function for formatting an xml document.  Adds indents and line breaks.
-----------------------------------------------------

function xml_format($xml) {
    // v 1.1, escapes backslash brackets //
    $xml = str_replace ("\n", "", $xml);
    $xml = str_replace ("\r", "", $xml);
    $xml = str_replace ("\\>", "&GT;", $xml);
    $xml = str_replace ("\\<", "&LT;", $xml);
    $out = preg_replace_callback("|\<[^\>]*\>[^\<]*|", "_xml_format_element", $xml);
    $out = str_replace ('&GT;', '>', $out);
    $out = str_replace ('&LT;', '<', $out);
    $out = str_replace ('<', '&lt;', $out);
    $out = str_replace ('>', '&gt;', $out);
    return nl2br($out);
}

function _xml_format_element($array) {
    // callback function for xml_format.  Do not invoke directly //
    $found = $array[0];
    static $indent;
    $found = trim($found);
    $tagOffset = 1;
    $openingText = "\n";
    $tab = str_repeat("&nbsp;", $indent * 4);
    if (substr($found, 0, 2)=='</') {
        // closing tag //
        $tagOffset = 2;
        $indent--;
        $tab = str_repeat("&nbsp;", $indent *4);
    } else if (substr($found, -2, 1)=='/' || strpos($found, '/>')) {
        // opening and closing tag //
        // do not change indent //
    } else {
        // opening tag //
        $indent++;
    }
    // $content = substr(strrchr($found, '>'), 0, -1);
    if (substr($found, -1) != '>') {
        // indent the content //
        $found = str_replace (">", ">\n" . str_repeat("&nbsp;", ($indent+0)*4), $found);
    }
    return $openingText . $tab . $found ;
}
jon.sprague(at)itgco.com
20-Feb-2002 04:54
This is what I did to get DOM to work with PHP on a Linux box.

1.
I installed zlib-1.1.3 from source (http://www.gzip.org/zlib/).
Don't forget the "./" in front of configure (the README leaves this out).

I did a ldconfig -v (and I checked to make sure libz is there).

2.
I installed libxml2-2.4.9 from source (ftp://ftp.gnome.org/pub/GNOME/stable/sources/libxml/).
I used the "--with-zlib" extention.
I looked at the output of configure to make sure it found zlib (looked something like this: "checking for zlib.h... yes").

I did a ldconfig -v (and I checked to make sure libxml is there).

3.
Then I installed PHP (ver. 4.1.1).
I used the "--with-dom --with-zlib" extentions.
I then made sure PHP recognized them by reading the output of configure:
(checking for DOM support... yes),
(checking if the location of ZLIB install directory is defined... no) I ignored this,
(checking whether to include ZLIB support... yes).

As always reading the INSTALL and/or README files help tremendously.

I hope this helps someone!
apinstein at mac dot NOSPAM dot com
10-Feb-2002 06:06
Hopefully this will help anyone who had as much trouble as I have using domxml across different PHP versions...

I am using 4.1.1 now, with libxml2-2.4.13.

It seems that the way the XML tree is represented has changed from 4.06/libxml2-2.3.14 to use multple node types.

I had a lot of trouble figuring out how to get to the TAGNAME and CONTENT data for my XML tree... but I figured it out and wanted to share:

function getNodeContent($name) {
    $child_a = domxml_children(domxml_root($doc));
    foreach ($child_a as $node) {
        if ($node->tagname() == $name) {
            // the CONTENT of a node is in the content field of a
            // CHILD node of the tag name.
            // <NODE>DATA</NODE> is actually a NODE element
            // object with a TEXT element object as its only child.
            // THe child TEXT element has the content field with
            // the actual content.
            // it helps a LOT to do a print_r(xmltree($xml)) and
            // look at this as HTML SOURCE because it's nicely indented
            $content_a = domxml_children($node);
            return $content_a[0]->content;
        }
    }
}
nacse at msn dot com
30-Jan-2002 05:48
Well, actually, it works. Try the following code:

<?php

    $myXML 
"<mrow><mo>Coca-Cola</mo></mrow>";

   
$docTree xmltree($myXML);
    print(
"<pre>");
   
   
# print whole document structure
   
print_r$docTree ); 

   
# print content of <mo> element
   
print $docTree->children[0]->children[0]->children[0]->content

    print( 
"</pre>" );
?>
madsosterby at mail1 dot stofanet dot dk
24-Nov-2001 10:27
DOMXML on Windows 9x!

I update this site frequently with latest news regarding Apache/PHP: www.mdz.dk

DOMXML
To make this work, I spend a year looking and trying to get the answer... here it is (I hope)--

Copy the file \php\php4ts.dll to c:\windows\system\

Open and edit "apache.conf". PHP MUST be loaded as a module,
or it wont work with domxml.

Here is a part of my apache.conf:


#ScriptAlias /php/ "c:/webserver/php/"
#AddType application/x-httpd-php .php   
#Action application/x-httpd-php "/php/php.exe   
LoadModule php4_module c:/webserver/php/sapi/php4apache.dll
AddType application/x-httpd-php .php

Now you should tjeck if you can start apache, and see that no errors occour. :)

Open "c:\windows\php.ini" in notepad.

Find and change these two lines to: (remember to change to rigth path!)

extension_dir= "c:\WebServer\php\extensions";
extension=php_domxml.dll

Now the Last part:

I got it to work with: a) libxml2-v.2.4.6 and b)libxml2-2.4.10

Download libxml2 from www.fh-frankfurt.de/~igor/projects/libxml/index.html.

Unpack and copy "lib2xml.dll" to "c:\windows\system\"

NOTE:
Using libxml2-v.2.4.10, you must also download "iconv binaries, version 1.7 for Win32" from the same site
and unpack "iconv.dll" to "c:\windows\system\"

Thats all.. I got it to work, so can you!

---- Test DOMXML

With phpInfo() you惻l see this somewhere on the page:

DOM/XML enabled
libxml Version 2.3.7
XPath Support enabled
XPointer Support enabled


This piece of code will write "What employees?" if domxml not is installed correct.

Note that a) you must have a file named employees.xml, and the you MUST write
down the whole path to the xml-file.

$doc = xmlDocfile("c:\webserver\xml\employees.xml") or die("What employees?");

Here is the proof that domxml can be runned under Windows 98. www.mdz.dk
dhoeckel at skilldeal dot com
11-May-2001 03:33
If you read your XML file with the fread() function, be carefull with the magic_quotes (compiler-) option. Magic Quotes _must_ be turned off before reading the data.
To be save use something like

set_magic_quotes_runtime(0);
before fread() and
set_magic_quotes_runtime(get_magic_quotes_gpc());
after.
06-Apr-2001 06:06
In addition to the symlinks to the compiled libs, there's the following one for the includes needed:
# ln -s /usr/local/include/libxml2/libxml /usr/lib/libxml
zoot at zotikos dot com
30-Dec-2000 06:35
check out an article about using DOM in php at
http://www.phpbuilder.com/columns/matt20001228.php3
marcel dot schwarz at mikan dot de
17-Aug-2000 06:39
Maybe it is of interest for someone:

This is an example for getting the attribute of a
node "article" using the xmldoc-function.

&lt;?php
$docnode = xmldoc("&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".
                  "<!DOCTYPE webdoctype SYSTEM \"webdoc.dtd\">\n".
                  "<webdoc>\n".
                  "  <article id=\"651\"/>\n".
                  "</webdoc>\n");

$node = $docnode->children();
$node = $node[1]->children();
$attr = $node[1]->attributes();
printf("%s=%s", $attr[0]->name, $attr[0]->children[0]->content);
?>
Daniel dot Veillard at w3 dot org
13-Aug-2000 01:46
I'm libxml maintainer, I suggest anybody using
the DOM functions to:
  - not stay with 2.0.x versions, upgrade please
     http://rpmfind.net/pub/libxml/
  - have a look at xmlsoft.org if you want more
     information, but this might be misleading too
     since PHP-DOM doesn't expose all the
     libxml API
  - for the DOM reference http://www.w3.org/TR/
  - if you have trouble when parsing an
    XML/HTML files, check first that they are
     correct (xmllint distributed with libxml may
     help), if no fix them, if yes send me a bug
     report with the input exhibiting the problem

 happy DOM hacking,

Daniel.Veillard@w3.org

<scandirDomAttribute->name>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST