|
|
 |
XXIV. Funzioni DOM XMLIntroduzione| Attenzione | Questo modulo è
SPERIMENTALE. Ovvero, il comportamento di queste
funzioni, i nomi di queste funzioni, in definitiva tutto ciò
che è documentato qui può cambiare nei futuri rilasci
del PHP senza preavviso. Siete avvisati, l'uso di questo modulo
è a vostro rischio. |
Nella versione 4.3.0 di PHP l'estensione DOM XML è stata rivista in modo
da fornire una migliore adesione allo standard DOM. Il modulo contiene ancora
diverse vecchie funzioni, ma non dovrebbero essere più usate. Specialmente
quelle funzioni non orientate agli oggetti.
Questo modulo permette di operare con un documento XML utilizzando API DOM.
Inoltre viene fornita una funzione, domxml_xmltree(), per convertire
l'intero documento XML in un albero di oggetti PHP. Attualmente questo
albero dovrebbe essere considerato di sola lettura, è possibile modificarlo, ma
questa operazione non avrebbe senso dato che la funzione DomDocument_dump_mem()
non può essere applicata
all'albero. Pertanto se si desidera leggere un file XML e scriverne una
versione modificata, occorre utilizzare le funzioni DomDocument_create_element(),
DomDocument_create_text_node(),
set_attribute(), ecc. ed infine
DomDocument_dump_mem().
Requisiti
Questo modulo utilizza la libreria
GNOME xml library. Fare il download
ed installare questa libreria. Occorre avere almeno la libxml-2.4.14.
Per potere utilizzare le caratteristiche previste nel DOM XSLT occorre
utilizzare libxslt library ed EXSLT
enhancements da http://www.exslt.org/. Scaricare
ed installare queste librerie se si prevede di utilizzare la funzioni
avanzate di XSLT. Occorre almeno la versione libxslt-1.0.18.
Installazione
Questo modulo è disponibile soltanto se il PHP è stato configurato con
--with-dom=[DIR]. Aggiungere
--with-dom-xslt[=DIR] per includere il supporto al
DOM XSLT support. DIR indica la directory in cui è installato libxslt. Aggiungere
--with-dom-exslt[=DIR] per includere il supporto
al DOM EXSLT, dove DIR indica la directory in cui è installato libexslt.
Nota per gli utenti Win32:
Per potere abilitare questa estensione sui sistemi Windows, occorre copiare
file addizionali dalla directory DLL della dustribuzione PHP/Win32
nella directory SYSTEM32 della macchina Windows (ad esempio: C\WINNT\SYSTEM32
oppure c:\WINDOWS\SYSTEM32). Per le versioni di PHP <= 4.2.0 copiare il file
libxml2.dll, per le versioni >= 4.3.0 copiare il file
>iconv.dll.
Funzioni deprecate
Esistono alcune funzioni che non rientrano nello standard DOM e quindi
non dovrebbero essere più utilizzate come evidenziato nella tabella seguente.
La funzione DomNode_append_child() ha modificato il suo
comportamento. Attualmente aggiunge un figlio e non un elemento fratello. Se ciò crea
problemi alle applicazioni si può usare la funzione non DOM
Tabella 1. Funzioni deprecate e loro sostituti | Vecchia funzione | Nuova funzione |
|---|
| xmldoc | domxml_open_mem() | | xmldocfile | domxml_open_file() | | domxml_new_xmldoc | domxml_new_doc() | | domxml_dump_mem | DomDocument_dump_mem() | | domxml_dump_mem_file | DomDocument_dump_file() | | DomDocument_dump_mem_file | DomDocument_dump_file() | | DomDocument_add_root | DomDocument_create_element() seguita da
DomNode_append_child() | | DomDocument_dtd | DomDocument_doctype() | | DomDocument_root | DomDocument_document_element() | | DomDocument_children | DomNode_child_nodes() | | DomDocument_imported_node | Nessun sostituto. | | DomNode_add_child | Creare un nuovo nodo con, ad esempio,
DomDocument_create_element() e aggiungere il figlio con
DomNode_append_child().
| | DomNode_children | DomNode_child_nodes() | | DomNode_parent | DomNode_parent_node() | | DomNode_new_child | Creare un nuovo nodo con, ad esempio,
DomDocument_create_element() e aggiungere il figlio con
DomNode_append_child().
| | DomNode_get_content | Il contenuto è semplicemente un nodo di testo ed è accessibile tramite
DomNode_child_nodes().
| | DomNode_set_content | Il contenuto è semplicemente un nodo di testo e può essere aggiunto con
DomNode_append_child().
|
Costanti predefinite
Queste costanti sono definite da questa estensione e
sono disponibili solo se l'estensione è stata compilata
nel PHP o se è stata caricata dinamicamente a runtime.
Tabella 2. Costanti XML | Costante | Valore | Descrizione |
|---|
|
XML_ELEMENT_NODE
(integer)
| 1 | Il nodo è un elemento | |
XML_ATTRIBUTE_NODE
(integer)
| 2 | Il nodo è un attributo | |
XML_TEXT_NODE
(integer)
| 3 | Il nodo è un segmento di testo | |
XML_CDATA_SECTION_NODE
(integer)
| 4 | | |
XML_ENTITY_REF_NODE
(integer)
| 5 | | |
XML_ENTITY_NODE
(integer)
| 6 | Il nodo è un'entità come, ad esempio, | |
XML_PI_NODE
(integer)
| 7 | Il nodo è una istruzione di processamento | |
XML_COMMENT_NODE
(integer)
| 8 | Il nodo è un commento | |
XML_DOCUMENT_NODE
(integer)
| 9 | Il nodo è un documento | |
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)
| | |
Classi
Le API di questo modulo aderiscono il più possibile allo standard
DOM di livello 2. Di conseguenza le API sono completamente orientate agli oggetti.
Si ritiene una buona idea avere disponibile lo standard DOM quando
si utilizza questo modulo.
Sebbene le API siano orientate agli oggetti, vi sono alcune funzioni che possono
essere richiamate in modo non orientato agli oggetti, passando l'oggetto su cui operare come
primo argomento. Queste funzioni sono state mantenute per compatibilità
verso le vecchie versioni del modulo, ma non se ne incoraggia l'uso nello
sviluppo di nuovi prodotti.
Queste API differiscono della API DOM ufficiali per due aspetti. Primo, gli attributi
della classe sono implermentati come funzioni con il medesimo nome e, secondo,
i nomi delle funzioni seguono la convenzione del PHP. Questo significa che
la funzione DOM lastChild() sarà chiamata last_child().
In questo modulo sono definite diverse classi, queste saranno elencate
- compresi i loro metodi -
nella seguente tabella. Le classi con un equivalente nello standard
DOM sono chiamate DOMxxx.
Tabella 3. Elenco delle classi | Nome della classe | Classe genitrice |
|---|
| DomAttribute | DomNode | | DomCData | DomNode | | DomComment | DomCData : DomNode | | DomDocument | DomNode | | DomDocumentType | DomNode | | DomElement | DomNode | | DomEntity | DomNode | | DomEntityReference | DomNode | | DomProcessingInstruction | DomNode | | DomText | DomCData : DomNode | | Parser | Attualmente chiamata DomParser | | XPathContext | |
Tabella 4. Classe DomDocument (DomDocument : DomNode) | Metodi | Funzioni | Note |
|---|
| doctype | DomDocument_doctype() | | | document_element | DomDocument_document_element() | | | create_element | DomDocument_create_element() | | | create_text_node | DomDocument_create_text_node() | | | create_comment | DomDocument_create_comment() | | | create_cdata_section | DomDocument_create_cdata_section() | | | create_processing_instruction | DomDocument_create_processing_instruction() | | | create_attribute | DomDocument_create_attribute() | | | create_entity_reference | DomDocument_create_entity_reference() | | | get_elements_by_tagname | DomDocument_get_elements_by_tagname() | | | get_element_by_id | DomDocument_get_element_by_id() | | | dump_mem | DomDocument_dump_mem() | non standard DOM | | dump_file | DomDocument_dump_file() | non standard DOM | | html_dump_mem | DomDocument_html_dump_mem() | non standard DOM | | xpath_init | xpath_init | non standard DOM | | xpath_new_context | xpath_new_context | non standard DOM | | xptr_new_context | xptr_new_context | non standard DOM |
Tabella 5. Classe DomElement (DomElement : DomNode) | Metodo | Funzioni | Note |
|---|
| tagname | DomElement_tagname() | | | get_attribute | DomElement_get_attribute() | | | set_attribute | DomElement_set_attribute() | | | remove_attribute | DomElement_remove_attribute() | | | get_attribute_node | DomElement_get_attribute_node() | | | get_elements_by_tagname | DomElement_get_elements_by_tagname() | | | has_attribute | DomElement_has_attribute() | |
Tabella 6. Classe DomNode | Metodo | Note |
|---|
| 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() | non standard DOM. Questa funzione emula il comportamento
di DomNode_append_child(). | | DomNode_remove_child() | | | DomNode_has_child_nodes() | | | DomNode_has_attributes() | | | DomNode_clone_node() | | | DomNode_attributes() | | | DomNode_unlink_node() | non standard DOM | | DomNode_replace_node() | non standard DOM | | DomNode_set_content() | non standard DOM, deprecata | | DomNode_get_content() | non standard DOM, deprecata | | DomNode_dump_node() | non standard DOM | | DomNode_is_blank_node() | non standard DOM |
Tabella 7. Classe DomAttribute (DomAttribute : DomNode) | Metodo | | Note |
|---|
| name | DomAttribute_name() | | | value | DomAttribute_value() | | | specified | DomAttribute_specified() | |
Tabella 8. Classe DomProcessingInstruction (DomProcessingInstruction : DomNode) | Metodo | Funzione | Note |
|---|
| target | DomProcessingInstruction_target() | | | data | DomProcessingInstruction_data() | |
Tabella 9. Classe Parser class | Metodo | Funzione | Note |
|---|
| add_chunk | Parser_add_chunk() | | | end | Parser_end() | |
Tabella 10. Classe XPathContext | Metodo | Funzione | Note |
|---|
| eval | XPathContext_eval() | | | eval_expression | XPathContext_eval_expression() | | | register_ns | XPathContext_register_ns() | |
Tabella 11. Classe DomDocumentType (DomDocumentType : DomNode) | Metodo | Funzione | Note |
|---|
| name | DomDocumentType_name() | | | entities | DomDocumentType_entities() | | | notations | DomDocumentType_notations() | | | public_id | DomDocumentType_public_id() | | | system_id | DomDocumentType_system_id() | | | internal_subset | DomDocumentType_internal_subset() | |
La classe DomDtd è derivata da DomNode. Mentre DomComment è derivata da
DomCData
Esempi
Diversi esempi presenti in questo manuale richiedono un testo XML. Anzichè
ripetere questo testo in ogni esempio, si inserirà il testo in un file
che verrà incluso in ogni esempio. Questo file di include verrà illustrato
nel seguente esempio. Si può anche creare un documento XML e
leggerlo con DomDocument_open_file().
Esempio 1. File di include example.inc con testo XML |
<?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'>
&sp;
<!-- comment -->
<informaltable ID='findme' language='&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>";
?>
|
|
add a note
User Contributed Notes
Funzioni DOM XML
SAM
22-Apr-2004 05:05
When installing PHP --with-dom and --with-dom-xslt on a Red Hat 9.0 remember to install the following packages:
libxml
libxml2
libxml2-devel
libxslt
libxslt-devel
Then you will be spared error messages when trying to configure.
regards
SAM
ngc(dontSpamMe)rapanden(SpamOFF)dk
28-Jan-2004 10:48
Sorry, a bug in my code... I made the first version late at night, sorry!
The bug was in the "if ($ChildDomNode->has_child_nodes())" block, I didn't save the data for the for the CildNode of the CildNodes. the bug has been fixed.
<?php
function getElementAttributes($DomNode,$elementName,$attriName)
{
if ($ChildDomNode = $DomNode->first_child())
{
while($ChildDomNode)
{
if ($ChildDomNode->node_type() == XML_ELEMENT_NODE)
{
if($ChildDomNode->node_name() == $elementName)
{
if ($ChildDomNode->has_attributes())
{
$Array = $ChildDomNode->attributes();
foreach ($Array AS $DomAttribute)
{
if($DomAttribute->name() == $attriName)
{
$nodeArray[] = $DomAttribute->value();
}
}}}
if ($ChildDomNode->has_child_nodes())
{
$tmpArray = (getElementAttributes($ChildDomNode,$elementName,$attriName));
$nodeArray = array_merge($nodeArray, $tmpArray);
unset($tmpArray);
}}$ChildDomNode = $ChildDomNode->next_sibling();
}return $nodeArray;
}}
$file = "test3.xml";
$element = "pb";
$att = "id";
$DomDocument = domxml_open_file($file);
$RootDomNode = $DomDocument->document_element();
$array = getElementAttributes($RootDomNode,$element,$att);
echo "<pre>";
print_r($array);
echo "</pre>";
?>
bps7j at yahoSPAMo.com
24-Dec-2003 06:19
bradparks at bradparks dot com
17-Dec-2003 08:41
phpdocs at pointbeing dot net
25-Nov-2003 06:43
FWIW, here's bart @ mediawave's extremely useful function, rewritten using current PHP coding conventions:
<?php
function PrintDomTree($DomNode)
{
if ($ChildDomNode = $DomNode->first_child()) {
static $depth = 0;
$whitespace = "\n<br>".str_repeat(" ", ($depth * 2));
while ($ChildDomNode) {
if ($ChildDomNode->node_type() == XML_TEXT_NODE) {
echo trim($ChildDomNode->node_value());
} elseif ($ChildDomNode->node_type() == XML_ELEMENT_NODE) {
$HasTag = 1;
echo $whitespace;
echo "<", $ChildDomNode->node_name();
if ($ChildDomNode->has_attributes()) {
$Array = $ChildDomNode->attributes();
foreach ($Array AS $DomAttribute) {
echo " ", $DomAttribute->name(), "=\"", $DomAttribute->value(), "\"";
}
}
echo ">";
if ($ChildDomNode->has_child_nodes()) {
$depth++;
if (PrintDomTree($ChildDomNode)) {
echo $whitespace;
}
$depth--;
}
echo "</", $ChildDomNode->node_name(), ">";
}
$ChildDomNode = $ChildDomNode->next_sibling();
}
return $HasTag;
}
}
?>
bart at mediawave dot nl
19-Nov-2003 12:49
If you're starting with DOM it's better to wait untill PHP5. PHP5 has a new and better DOM implementation. I think it is not backwards compatible with this DOM extensions.
bart at mediawave dot nl
11-Nov-2003 05:46
This recursive function will iterate over a DOM object and display it as a nicely formatted XML structure. I used intuitive variable names to help learn more about the DOM functions and their return values.
<?php
function PrintDomTree($DomNode) {
if ($ChildDomNode = $DomNode->first_child()):
static $depth = 0;
$whitespace = "\n<br>".str_repeat(" ", ($depth * 2));
while($ChildDomNode):
if ($ChildDomNode->node_type() == XML_TEXT_NODE):
echo trim($ChildDomNode->node_value());
elseif ($ChildDomNode->node_type() == XML_ELEMENT_NODE):
$HasTag = 1;
echo $whitespace;
echo '<', $ChildDomNode->node_name();
if ($ChildDomNode->has_attributes()):
$Array = $ChildDomNode->attributes();
foreach ($Array AS $DomAttribute):
echo ' ', $DomAttribute->name(), '="', $DomAttribute->value(), '"';
endforeach;
endif;
echo '>';
if ($ChildDomNode->has_child_nodes()):
$depth++;
if (PrintDomTree($ChildDomNode)):
echo $whitespace;
endif;
$depth--;
endif;
echo '</', $ChildDomNode->node_name(), '>';
endif;
$ChildDomNode = $ChildDomNode->next_sibling();
endwhile;
return $HasTag;
endif;
}
$DomDocument = domxml_open_mem($xmlstr);
$RootDomNode = $DomDocument->document_element();
PrintDomTree($RootDomNode);
?>
brad
03-Nov-2003 09:33
> check out an article about using DOM in php at
> http://www.phpbuilder.com/columns/matt20001228.php3
This article is out of date, and no longer works with the latest rev of the DOM now available. Only look at this if you plan on using an older version of PHP (e.g. 4.0.6)
nospam at phppatterns dot com
09-Apr-2003 07:51
sorn at dsl dot upc dot es
17-Mar-2003 09: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-
zoot at zotikos dot com
29-Dec-2000 08:35
Daniel dot Veillard at w3 dot org
12-Aug-2000 05: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
| |