downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

domxml_open_mem> <domxml_new_doc
[edit] Last updated: Fri, 25 May 2012

view this page in

domxml_open_file

(PHP 4 >= 4.2.0)

domxml_open_fileCrea un objeto DOM a partir de un archivo XML

Descripción

DomDocument domxml_open_file ( string $filename [, int $mode = DOMXML_LOAD_PARSING [, array &$error ]] )

Esta función analiza el documento XML en el archivo dado.

Parámetros

nombre_archivo

La ruta al archivo XML. El archivo es accesado en modo de sólo-lectura.

modo

Este parámetro opcional puede ser usado para modificar el comportamiento de esta función.

Puede usar una de las siguientes constantes para este parámetro: DOMXML_LOAD_PARSING (predeterminado), DOMXML_LOAD_VALIDATING o DOMXML_LOAD_RECOVERING. También puede agregar DOMXML_LOAD_DONT_KEEP_BLANKS, DOMXML_LOAD_SUBSTITUTE_ENTITIES y DOMXML_LOAD_COMPLETE_ATTRS con una operación OR de bits.

error

Si se usa, contendrá los mensajes de error. error debe ser pasado por referencia.

Valores devueltos

Devuelve una instancia DomDocument del archivo dado.

Ejemplos

Ejemplo #1 Apertura de un documento XML desde un archivo

<?php

if (!$dom domxml_open_file("ejemplo.xml")) {
  echo 
"Ocurrió un error al analizar el documento\n";
  exit;
}

$raiz $dom->document_element();
?>

Historial de cambios

Versión Descripción
4.3.0 Fueron agregados los parámetros modo y error.

Ver también



domxml_open_mem> <domxml_new_doc
[edit] Last updated: Fri, 25 May 2012
 
add a note add a note User Contributed Notes domxml_open_file
koms at koms dot ru 03-Mar-2009 04:18
The way to order the nodes in XML-files by an attribute (desc or asc):

<?php
// open the XML-file
$xml = domxml_open_file("our_file.xml");

// get the root element
$root = $xml->document_element();
// get the list of the nodes
$nodes = $root->child_nodes();

// create the array 'messages' of the nodes
foreach($nodes as $node)
{
 if (
$node->node_name() == 'photo')
 {
    
$currentMessage['thumbnail'] = $node->get_attribute('thumbnail');
    
$currentMessage['filename'] = $node->get_attribute('filename');
    
$currentMessage['idnum'] = $picnum[md5($node->get_attribute('filename'))];
    
$messages[] = $currentMessage;
 }
}

// sort all the nodes by idnum (asc/desc is "1: -1" or "-1: 1")
$compare_func = create_function('$a, $b', 'return ($a[\'idnum\']==$b[\'idnum\'])? 0: (($a[\'idnum\']>$b[\'idnum\'])? 1: -1);');
usort($messages, $compare_func);

// create the new XML-data
$doc = domxml_new_doc("1.0");
$root = $doc->create_element("photos");
$root = $doc->append_child($root);
for(
$ee=0;$ee<count($messages);$ee++)
{
   
$msgNode = $root->new_child('photo');
    foreach(
$messages[$ee] as $description => $result)
    {
       
$msgNode->set_attribute($description,$result);
    }
}

// write down the XML-file
$text = $doc->dump_mem(true);
$fp = fopen("our_file.xml","w");
fwrite($fp,$text);
fclose($fp);
?>
A-Wing (info at a-wing dot co dot uk) 16-May-2006 05:23
A very useful undocumented feature if you are opening hundreds of xml docs (my script processes 20,000) is DomDocument->free.
This clears the allocated the memory used by the xml file which is not done automatically by just opening a new file on the same variable.

Example:

<?
$dir="/path/to/xml/files/";
if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
        if(is_file($dir.$file))
        {
            echo $file . "\\n";
            $dom=domxml_open_file($dir.$file);

            #...
            #You xml processor here
            #...
            $dom->free();
        }
    }
    closedir($dh);
}

?>
noyanoya at tin dot it 28-Dec-2005 02:47
another way to resolve path's problem is to use  realpath() function
for example:

<?php
$file
=$_REQUEST['file'];
$xmlPath = realpath("../xml/");
$fileXML ="$file";
  if(!
$dom = domxml_open_file($xmlPath."/".$fileXML)) {
    echo
"error opening the file";
    exit;
}
?>

N.B. you have to put the final slash ( / ) beetween path and file name!
php at gungfu [dot] de 19-Mar-2005 01:13
For me, on Windows XP, the solution with  file_get_contents works, the one with domxml_open_file does not. It seems the latter caches the loaded file. Quite confusing.
contact at richardleggett dot co dot uk 14-Feb-2005 07:00
If you want to work on both Windows and Linux, I found appending the following to the front of your file path works:

$xmlPath = dirname(__FILE__) . "/";
$xmlDOM = domxml_open_file($xmlPath . "file.xml");

(rather than the "\\" in a previous post on this page which only works on Windows).

This should get around the I/O errors.
info at sgonda dot de 30-Oct-2003 06:02
You can load your own DTD's within your XML Doc like this:

<?php
$domxml
= domxml_open_file('test.xml',DOMXML_LOAD_VALIDATING,$error);
?>

I hope this helps....

The DocumentType Definition (must/have) to be in the Doc root of your Server...
kevin at ieqdev dot com 15-Jun-2003 10:30
If you're working on a windows machine and don't want to use full paths , just use...

$showfile = file_get_contents($path . "/" . $fileName);

if(!$domDoc = domxml_open_mem($showfile)) {
    echo "Couldn't load xml...";   
    exit;
}

Because file_get_contents() can use relative paths on Win, it keeps your code more portable...

twist
et at wkv dot at 24-Feb-2003 01:49
domxml documentation is a moving target, for 4.2.3 a working example is:

<?
$xmlpath = dirname(__FILE__) . "\\";
$xmldoc = domxml_open_file( $xmlpath . "test.xml");
$xsldoc = domxml_xslt_stylesheet_file ( $xmlpath . "test.xsl");
$result = $xsldoc->process($xmldoc);
print $result->dump_mem();
?>

RTFS is a working method in this case (lucky guesses work also from time tor time) :-)
andrew at boxuk dot com 06-Feb-2003 10:32
Using PHP 4.2.3 and Win2K.

The XML file needs to be referenced using the full filesystem path name, even if its in the same directory.
rudolfnospam at redshift dot co dot no dot spam dot za 29-Apr-2002 12:12
Using PHP 4.1.2, Win2K, IIS.
I found that if the path to the XML source file is too long then the file isn't picked up. I haven't tested it to see how long the path can be or whether this is still an issue in PHP 4.2

 
show source | credits | stats | sitemap | contact | advertising | mirror sites