PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<rewinddirDomAttribute->name>
view the version of this page
Last updated: Sat, 19 Apr 2003

XXV. DOM XML Funktionen

Einf�hrung

Warnung

Diese Erweiterung ist EXPERIMENTELL. Das Verhalten dieser Erweiterung, einschlie�lich der Funktionsnamen, und alles Andere was hier dokumentiert ist, kann sich in zuk�nftigen PHP-Versionen ohne Ank�ndigung �ndern. Seien Sie gewarnt und verwenden Sie diese Erweiterung auf eigenes Risiko.

Die DOM XML Erweiterung wurde in PHP 4.3.0 �berholt, um dem DOM Standard besser zu entsprechen. Die Erweiterung enth�lt noch immer viele alte Funktionen, die aber nicht mehr benutzt werden sollten. Im Besonderen sollten nicht objektorientierte Funktionen vermieden werden.

Diese Erweiterung erlaubt es, an einem XML Dokument mit dem DOM API zu arbeiten. Sie bietet auch die Funktion domxml_xmltree(), um das gesamte XML Dokument in einen Baum von PHP Objekten zu verwandeln. Zur Zeit sollten Sie diesen Baum nur zum Lesen verwenden — Sie k�nnen ihn zwar modifizieren, aber nachdem DomDocument_dump_mem() nicht darauf angewendet werden kann, macht dies keinen Sinn. Sollten Sie eine XML Datei lesen und eine modifizierte Version schreiben wollen, benutzen Sie die Funktionen DomDocument_create_element(), DomDocument_create_text_node(), set_attribute(), etc. und schlie�lich DomDocument_dump_mem().

Anforderungen

Diese Erweiterung macht von der Gebrauch. Laden Sie diese bitte herunter und installieren Sie diese Bibliothek. Sie werden zumindest libxml-2.4.14 ben�tigen. Um DOM XSLT Features zu benutzen, k�nnen Sie die und EXSLT Erweiterungen von verwenden. Laden Sie diese Bibliotheken herunter und installieren Sie diese, wenn Sie den Einsatz von (erweiterten) XSLT Features planen. Sie werden zumindest libxslt-1.0.18 ben�tigen.

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 libxml2.dll 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)

Veraltete Funktionen

Es gibt ziemlich viele Funktionen, die nicht in den DOM Standard passen und nicht mehr l�nger benutzt werden sollten. Diese Funktionen sind in der folgenden Tabelle aufgelistet. Die Funktion DomNode_append_child() hat ihr Verhalten ge�ndert, indem sie nun ein 'Kind' statt einem 'Geschwister' hinzuf�gt. Wenn Ihre Applikation deshalb nicht mehr funktioniert, verwenden Sie die nicht DOM standardkonforme Funktion DomNode_append_sibling().

Tabelle 1. Veraltete Funktionen und deren Ersatz

Alte FunktionNeue Funktion
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() gefolgt von DomNode_append_child()
DomDocument_dtdDomDocument_doctype()
DomDocument_rootDomDocument_document_element()
DomDocument_childrenDomNode_child_nodes()
DomDocument_imported_nodeKein Ersatz.
DomNode_add_childErstellen Sie einen neuen Knoten mit z.B. DomDocument_create_element() und f�gen Sie ihn mit DomNode_append_child() hinzu.
DomNode_childrenDomNode_child_nodes()
DomNode_parentDomNode_parent_node()
DomNode_new_childErstellen Sie einen neuen Knoten mit z.B. DomDocument_create_element() und f�gen Sie ihn mit DomNode_append_child() hinzu.
DomNode_set_contentErstellen Sie einen neuen Knoten mit z.B. DomDocument_create_text_node() und f�gen Sie ihn mit DomNode_append_child() hinzu.
DomNode_get_contentDer Inhalt ist nur ein Textknoten, auf den mittels DomNode_child_nodes() zugegriffen werden kann.
DomNode_set_contentDer Inhalt ist nur ein Textknoten, der mittels DomNode_append_child() hinzugef�gt werden kann.

Vordefinierte Konstanten

Folgende Konstanten werden von dieser Erweiterung definiert und stehen nur zur Verf�gung, wenn die Erweiterung entweder statisch in PHP kompiliert oder dynamisch zur Laufzeit geladen wurde.

Tabelle 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)   

Klassen

Das API dieses Moduls entspricht dem DOM Level 2 Standard so weit wie m�glich. Folglich ist das API vollst�ndig objektorientiert. Es w�re sinnvoll, den DOM Standard verf�gbar zu haben, wenn Sie dieses Modul benutzen. Obwohl das API objektorientiert ist gibt es viele Funktionen, die in einer nicht objektorientierten Art aufgerufen werden k�nnen, indem das zu bearbeitende Objekt als das erste Argument �bergeben wird. Diese Funktionen dienen haupts�chlich der Kompatibilit�t zu �lteren Versionen dieser Erweiterung und sollten deshalb beim Erstellen neuer Skripte nicht mehr verwendet werden.

Dieses API unterscheidet sich von dem offiziellen DOM API auf zwei Arten. Erstens sind alle Klassenattribute als Funktionen mit dem selben Namen implementiert. Zweitens folgen die Funktionsnamen der PHP Namenskonvention. Das hei�t, dass eine DOM Funktion lastChild() als last_child() geschrieben wird.

Dieses Modul definiert eine Anzahl Klassen, die — inklusive ihrer Methoden — in den folgenden Tabellen aufgelistet sind. Klassen mit einem �quivalent im DOM Standard werden DOMxxx genannt.

Tabelle 3. Liste der Klassen

KlassennameBasisklassen
DomAttributeDomNode
DomCDataDomNode
DomCommentDomCData : DomNode
DomDocumentDomNode
DomDocumentTypeDomNode
DomElementDomNode
DomEntityDomNode
DomEntityReferenceDomNode
DomProcessingInstructionDomNode
DomTextDomCData : DomNode
ParserDerzeit noch immer DomParser genannt
XPathContext 

Tabelle 4. DomDocument Klasse (DomDocument : DomNode)

MethodennameFunktionsnameAnmerkung
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()kein DOM Standard
dump_fileDomDocument_dump_file()kein DOM Standard
html_dump_memDomDocument_html_dump_mem()kein DOM Standard
xpath_initxpath_initkein DOM Standard
xpath_new_contextxpath_new_contextkein DOM Standard
xptr_new_contextxptr_new_contextkein DOM Standard

Tabelle 5. DomElement Klasse (DomElement : DomNode)

MethodennameFunktionsnameAnmerkung
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() 

Tabelle 6. DomNode Klasse

MethodennameAnmerkung
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()Nicht im DOM Standard. Diese Funktion emuliert das fr�here Verhalten von DomNode_append_child().
DomNode_remove_child() 
DomNode_has_child_nodes() 
DomNode_has_attributes() 
DomNode_clone_node() 
DomNode_attributes() 
DomNode_unlink_node()Nicht im DOM Standard
DomNode_replace_node()Nicht im DOM Standard
DomNode_set_content()Nicht im DOM Standard, veraltet
DomNode_get_content()Nicht im DOM Standard, veraltet
DomNode_dump_node()Nicht im DOM Standard
DomNode_is_blank_node()Nicht im DOM Standard

Tabelle 7. DomAttribute Klasse (DomAttribute : DomNode)

Methodenname Anmerkung
nameDomAttribute_name() 
valueDomAttribute_value() 
specifiedDomAttribute_specified() 

Tabelle 8. DomProcessingInstruction Klasse (DomProcessingInstruction : DomNode)

MethodennameFunktionsnameAnmerkung
targetDomProcessingInstruction_target() 
dataDomProcessingInstruction_data() 

Tabelle 9. Parser Klasse

MethodennameFunktionsnameAnmerkung
add_chunkParser_add_chunk() 
endParser_end() 

Tabelle 10. XPathContext Klasse

MethodennameFunktionsnameAnmerkung
evalXPathContext_eval() 
eval_expressionXPathContext_eval_expression() 
register_nsXPathContext_register_ns() 

Tabelle 11. DomDocumentType Klasse (DomDocumentType : DomNode)

MethodennameFunktionsnameAnmerkung
nameDomDocumentType_name() 
entitiesDomDocumentType_entities() 
notationsDomDocumentType_notations() 
public_idDomDocumentType_public_id() 
system_idDomDocumentType_system_id() 
internal_subsetDomDocumentType_internal_subset() 

Die Klasse DomDtd ist von DomNode, und DomComment von DomCData abgeleitet

Beispiele

Viele Beispiele in dieser Referenz erfordern einen XML String. Anstatt diesen String laufend zu wiederholen, wird er in eine Datei geschrieben, die von jedem Beispiel eingebunden wird. Diese einzubindende Datei wird in dem folgenden Beispielteil gezeigt. Alternativ dazu k�nnen Sie ein XML Dokument erstellen, und dieses mit DomDocument_open_file() einlesen.

Beispiel 1. Einzubindende Datei example.inc mit 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>";
?>

Inhaltsverzeichnis
DomAttribute->name --  Gibt den Namen eines Attributes zur�ck.
DomAttribute->specified --  �berpr�ft, ob ein Attribut gesetzt ist.
DomAttribute->value --  Gibt den Wert eines Attributes zur�ck.
DomDocument->add_root [deprecated] --  F�gt ein Wurzelelement hinzu.
DomDocument->create_attribute --  Generiere ein neues Attribut.
DomDocument->create_cdata_section --  Generiere ein neues cdata-Element
DomDocument->create_comment --  Generiere eine neues Kommentarelement
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 --  Generiert eine neue Ausf�hrungsanweisung
DomDocument->create_text_node --  Generiere ein neues Textelement
DomDocument->doctype --  Gibt den Dokumententyp zur�ck
DomDocument->document_element --  Gibt das Wurzelelement zur�ck
DomDocument->dump_file --  Schreibt den internen XML-Baum zur�ck in eine Datei
DomDocument->dump_mem --  Schreibt den internen XML-Baum in eine Zeichenkette
DomDocument->get_element_by_id --  Sucht nach einem Element mit eine bestimmten ID
DomDocument->get_elements_by_tagname -- 
DomDocument->html_dump_mem --  Schreibt den internen XML-Baum als HTML in eine Zeichenkette
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_attributess --  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


User Contributed Notes
DOM XML Funktionen
add a note
Daniel dot Veillard at w3 dot org
12-Aug-2000 06:46

I'm libxml maintainer, I suggest anybody using
the DOM functions to:
 - not stay with 2.0.x versions, upgrade please
   
- 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
 - 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,

[email protected]

plalande (at) gameloft (dot) com
15-Aug-2000 06:10

It should also be noted that the presence of zlib compression library is necessary in order to compile php with DOM XML support.
marcel dot schwarz at mikan dot de
17-Aug-2000 11: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);
?>

loic at gnu dot org
06-Nov-2000 04:03

As of libxml-2.2.7 and php-4.0.2, the DOM API is *not* implemented. You cannot expect to read the W3C DOM reference manual and use the function names, this will not work. The php-4.0.2 "DOM" implementation offer important functionalities to work with XML documents but its name is misleading.
zoot at zotikos dot com
29-Dec-2000 09:35

check out an article about using DOM in php at

jmcastagnetto at php dot net
01-Mar-2001 05:45

(Copying note posted to the wrong section):

[email protected]
          24-Feb-2001 01:43pm
          To install domxml under Windows, runnning Apache with php4.04.

          Add two lines in c:\windows\php.ini under "Windows extensions"

         extension_dir=c:\php\extensions          
extension=c:\php_domxml.dll

                    / Mads �sterby

hlecuanda at autologue dot com
01-Mar-2001 09:17

when configuring DOM-XML on FreeBSD, i ran into some trouble. Just make sure that you have previously installed the following ports: libiconv and libxml2.

Then edit the Makefile on freebsd's port of php4. adding the line --with-dom=/usr/local. Make sure you use FreeBSD's port, 'cause if you try to build php from the basic distribution you will be missing several FreeBSD patches for trouble-free building. =)

After that, create symbolic links like these:

libxml.a -> libxml2.a

libxml.so -> libxml2.so.5

on /usr/lib . it should compile and install correctly.

05-Apr-2001 11: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

jw at shapers dot nl
08-May-2001 05:39

xpath_new_context(), as well as xpath_eval() are members of xmldoc object as of 4.0.6-dev. Aslo a lot of function names have changed. Better take a look at the header files (in php4.0.6/ext/domxml/) instead of the summary above. But xpath works much better than in 4.0.4!
dhoeckel at skilldeal dot com
10-May-2001 08: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.

hlecuanda at autologue dot com
12-May-2001 12:59

An alternative to turning off magic quotes is the stripslashes() function:


$xmldata = stripslashes(fread ($fd, filesize ($filename)));


Then, you can domxml $xmldata all you want. =) (makes for cleaner code)

uros at sir-mag dot com
09-Jun-2001 01:54

I tried to use domxml with 4.0.5 on FreeBSD.

[email protected] helps me a lot but he makes some mistake in second post

# ln -s /usr/local/include/libxml2/libxml /usr/include/libxml

or even

# ln -s /usr/local/include/libxml2/libxml /usr/local/include/libxml

is the right answer.

I bult without problems now.

Thanks

marc at modulform dot de
21-Jun-2001 04:51

If I read from a domxml instance I created, the attribute

$mydomxml->type

may contain 14 numbers according to the table above. anybody knows what it means that both XML_ELEMENT_NODE and XML_GLOBAL_NAMESPACE are represented by 1 resp. XML_ATTRIBUTE_NODE and XML_LOCAL_NAMESPACE by 2? context?

tr at wojo dot de
05-Sep-2001 06:22

WINDOWS PHP_DOMXML PROBLEM

i have a solution for the php_domxml.dll problem in win. you have to download the binary version of libxml for windows and copy them into your windows system directory (e.g. c:\winnt\system32 or c:\windows\system).

that's it - all will be load fine!

wes at vacubomb dot com
24-Sep-2001 10:10

Quite possibley the most useful class ever to grace php, phpDOM
-

manatlan at manella dot com
07-Oct-2001 05:40

there is a function to delete a node, in the DOMXML API !!!! (since 4.04 i believe) ...

domxml_unlink_node( node );

sure !

amirlaherNOSPAM at hotmail dot NO_SPAM dot com
09-Oct-2001 07:50

I have encountered various problems getting Dom XML to run on both Linux and NT [but never on 2000], sometimes dependant on the actual release of PHP 4.
If you are just parsing some xml, save time by using PHP's standard XML functions. Easy to use, well documented. Sorted timesaver :)

good at example dot com
06-Nov-2001 03:35

php changed the name of the attributes from 'name' to 'tagname', the member function 'getattr' no longer available but 'get_attribute' is still there.
jvm at gopinocchio dot com
15-Nov-2001 12:37

On 26-Sep-2001 "stevenf at shellnet dot co dot uk" posted a message about compiling php on FreeBSD.

The same problem he's talking about goes for RedHat 7.1.
If you installed libxml2-2.4.10 you have to make a symbolic link from /usr/include/libxml to /usr/include/libxml2/libxml.
Now the php configure script will find the DOM path.

madsosterby at mail1 dot stofanet dot dk
24-Nov-2001 01: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�ll 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

bjlan at hotmail dot com
22-Dec-2001 03:46

It seems like DomNode class attribute 'name' has changed to 'tagname' for nodes of type XML_TEXT_NODE.

The documentation does not mention anything about the changes to domxml (seems to be more than this one).

dietmar dot glachs at salzburgresearch dot at
07-Jan-2002 01:31

Work-Around for the unlink-problem ...

With the new version of php 4.1.x, the unlink-function does not work as expected - in my case - the script hangs up and is interrupted after the timeout ...

The following code is a simple work-around:

$useless = domxml_node( "newnode" );
$useless->append_child( $node_to_unlink );

The append_child-method simply appends the node to the $useless node and removes it automatically from the original tree. Doing nothing with $useless gives you the desired result.

Regards

rcherry at raysoft dot net
23-Jan-2002 12:04

I have an application which works perfectly in 4.0.6, but not 4.1.1.  A few notes about the new version:

node_name works
node_value does NOT work
nodes no longer have a contents property, and it is not clear how to get the contents of a node.

nacse at msn dot com
30-Jan-2002 08: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>" );
?>

apinstein at mac dot NOSPAM dot com
10-Feb-2002 09: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;
       }
   }
}

jon.sprague(at)itgco.com
19-Feb-2002 07: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 ().
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 ().
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!

james dot elkins at usinfotel dot com
07-Mar-2002 12:42

Note that any line breaks or white space between child tags will be interpreted as child text nodes. These need to be stripped out to get an accurate array of child nodes.
sbarnum at pointsystems com
15-Mar-2002 09: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 ;
}

oscar dot porcar at lideram dot com
30-Apr-2002 12:58

in the manual says that some function are deprecated, but when I try to use the new functions they are not implementet and I have to use the old ones.

Example:
xmldocfile  --  domxml_open_file()

Have I to upgrade or to installa any external library ??

I'm using Win32 platform to develop.
PHP-4.2.0
IIS-5.0

thank you

nlaine at filfog dot com
14-May-2002 01:52

Regarding the notes from
[email protected]
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:




enjoy urself !
ncik

ser at bds dot ru
20-Jun-2002 05:23

I have one huge problem when i use XPath implementation. My operative sysem says that PHP script tries to get some unreachable memory.
It occures when i parse an XML document with help of XPath. I found that it depends on file size. What can i do?

steve at stevedix dot de
03-Jul-2002 03:54

Note that attempting to compile both the DOMXML and XMLRPC libraries

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

into php will cause linking errors.

chiefgeek (at) ecodedesign.com
26-Jul-2002 12: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
*/
?>

jesse dot lovedatspam at spamilicious-hdm dot com
30-Aug-2002 10:09

Chiefgeek, thanks for figuring some of this new stuff out.

domxml_xslt_stylesheet_doc  is most likely going to take an Object of the DomDocument class, that represents your stylesheet.  That function, along with the others you mentioned, pretty much covers any possible way to create a  XsltStylesheet Object.

Why, you might ask, would you want to create an XsltStylesheet object out of a stylesheet you already have as a doc object?  The existing doc object is of the class DomDocument, and does not have the ->process() method that is so nice.

Xsltstylesheet->process has one required parameter: the DomDocument of the XML you want to style.  It also appears to have two optional parameters, one array of xslt parameters, and one boolean (?) for xpath parameters, though in the code I don't see the second one doing anything yet...

voland at cms dot ru
05-Sep-2002 11:29

some notes about chiefgeek (at) 25-Jul-2002 06:13  example.

If you have a deal with xml/xslt files with different encodings (other, than utf) - html_dump_mem can't be used to get html output.
There are special functions in � API of libxslt (xsltSaveResult*) , they look at params of <xsl:output> line in your xslt and set proper encoding (using API function htmlSetMetaEncoding) and after that it dump html with htmlDocContentDumpFormatOutput (all function names - libxml � API function).

In short - we need php interface to � function xsltSaveResultToString (at least) of libxslt to get xslt transform with libxml/libxslt . But i didn't saw this in current todo for php domxml module.

voland at cms dot ru
05-Sep-2002 12:19

uups - the things go faster than i expected
there are many good news from cvs :)
now we have
result_dump_mem and result_dump_file methods of xslt object. In the example above try $xsltdom->result_dump_mem();  :)

kievman at ukrpost dot net
01-Nov-2002 11:22

How call constructor of class DomDocument?

class MyDOM extends DomDocument
{
   function MyDOM()
   {
      parent::DomDocument() // <- ????
   }
}

krator at krator dot com
05-Nov-2002 02: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;
?>

chuck at ludwigsen dot org
22-Nov-2002 09:11

I am trying to submit a DOM XML document from JavaScript to a PHP page.  I can verify that the JS is making the XML Document correctly and that the PHP script can process an XML Document correctly.

My problem is that it seems like either (a) the Javascript xmlHttp.send(xmlDoc) is not sending the XML Document as a POST variable  or (b) my PHP instance isn' t receiving POST variables.  I've tried $_POST, $_FILES, $HTTP_POST_VARS, you name it.

I would appreciate any help.  Here is some code...

Javascript
---------------
var postStr  = "<myrec>";
   postStr += "<rowNumber>"+rowNumber+"</rowNumber>";
  postStr += "<itemNumber>"+itemNumber+"</itemNumber>";
  postStr += "<itemSize>"+itemSize+"</itemSize></myrec>";
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(postStr);

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
var url="test_validator.php";
xmlHttp.open("POST", url, false);
xmlHttp.send(xmlDoc);
var text=xmlHttp.responseText
var myOutput = document.getElementById('output');
myOutput.innerText=text;

PHP
------------
<?php
 require "./domxml_xmlarray.php";

 $xmlDoc = domxml_open_mem($_POST);
 $xmlTree = domxml_xmlarray($xmlDoc);

print ("<pre>");
 print_r ($HTTP_POST_VARS);
print_r ($_POST);
 print_r ($_REQUEST);
 print_r ($_FILES['userfile']['tmp_name']);
 print_r ($xmlTree);
 print ("</pre>");
?>

veebeesix at yahoo dot com
28-Nov-2002 04: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

veebeesix at yahoo dot com
28-Nov-2002 04: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

01-Feb-2003 11: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:



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();

?>

dannie at mapmechanics dot com
25-Feb-2003 06:00

ISSUE: Not loading php_domxml.dll
System: WINDOWS XP / 2000 pro
PHP version: 4.3.1

For all those people who have tried installing the libxml2.dll and are still receiving the message about could not load the module:

Extract the iconv.dll from the w32 zip, and put it in your windows\system32 (winnt\system32 on 2k)

it should now load in - no probs

enjoy
Dannie

dgraf at mail dot ru
02-Mar-2003 02: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



Luck !

sorn at dsl dot upc dot es
17-Mar-2003 10: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-

bobchao at ms1 dot url dot com dot tw
23-Mar-2003 10:26

on Win32 (win 2000 server/php 4.3.1):

For people who get lastest iconc.dll (v1.8):
Don't copy that file to your system32 or you get "Access Denied".
Just copy the one you get from PHP/Win32 pack to system32. It should be work.

pbougrier at micropole-univers dot com
04-Apr-2003 10: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�j�-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�j�-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

nospam at phppatterns dot com
09-Apr-2003 08:51

If you're having trouble understanding how the the DOM XML extension fits together you may find the UML diagram here helps:
mrowe at pointsystems dot com
17-Apr-2003 01:57

it looks like "libxml2.dll" isn't included with the 4.3.1 windows distribution.
Nick Payne-Roberts
26-Apr-2003 07:05

Just a note regarding the error you get when trying to complie --with-dom: configure: error: Please reinstall the libxml >= 2.4.14 distribution.

It means you need libxml2-devel package, not libxml or libxml2.

add a note

<rewinddirDomAttribute->name>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Mon May 12 21:12:21 2003 CEST