Foros del Web » Programando para Internet » PHP »

como hago para parser un xml???

Estas en el tema de como hago para parser un xml??? en el foro de PHP en Foros del Web. hola a todos ya e probado con todas las classes avidas y por aver pero nada no hay forma que funcione, me gustria que si ...
  #1 (permalink)  
Antiguo 06/05/2005, 10:01
Avatar de alexjnm  
Fecha de Ingreso: octubre-2004
Ubicación: cuba
Mensajes: 218
Antigüedad: 19 años, 5 meses
Puntos: 1
como hago para parser un xml???

hola a todos
ya e probado con todas las classes avidas y por aver pero nada no hay forma que funcione, me gustria que si pueden me ayuden soy nuevo en esto de xml para llevarlo a php nose como hacerlo. Si conosen algun sitio donde haya documentacion se lo agradeseria
saludos alex
__________________
__________________________________________________ _________
A beses el camino mas largo es la solución mas eficaz :)
  #2 (permalink)  
Antiguo 06/05/2005, 11:25
Avatar de sism82  
Fecha de Ingreso: octubre-2003
Ubicación: Guadalajara
Mensajes: 865
Antigüedad: 20 años, 5 meses
Puntos: 1
pues no se donde hayas buscado, pero la red esta repleta de esa clase de información, para prueba basta consultar la documentación de php para la función xml_parse_into_struct y similares.

Adicionalmente te dejo esta clase, unicamente la escribí y probe ligeramente, puede contener algún error de lógica bajo condiciones extrañas. Pero creo que está entendible.

Código PHP:
<?php
/********************* Xml_Config  ******************/
/*
this class uses the php xml parser to construct a multidimensional array with the values of an XML file
*/
include_once('dbLink.php');
class 
Xml_Config {
    
    protected 
$db      NULL;
    public 
$xml_parser NULL;
    public 
$xml_values = array();
    public 
$xml_indexs = array();
    public 
$xml_struct = array();
    public 
$xml_data   "";
    public 
$xml_file   "";
    
    public function 
__construct($file "") {
        
$this->xml_parser           xml_parser_create();
        
$this->db                   = new dbLink();
        if ( 
$file != "" ) {
            
$this->setXmlFile($file);
            return 
$this->readXml();
        } else {
            return 
true;
        }
    }
    
    public function 
setXmlFile($file) {
        
$this->xml_file $file;
        return 
true;
    }
    
    public function 
readXml() {
        if ( 
is_file($this->xml_file) && is_readable($this->xml_file) ) {
            
$data file_get_contents($this->xml_file);
            
xml_parse_into_struct($this->xml_parser,$data,$this->xml_values,$this->xml_indexs);
            
$this->xml_values $this->xmlRemoveCdata($this->xml_values);
            
$xml_level_tags $this->getXmlLevelTags(1);
            
$this->createXmlStruct($xml_level_tags,$this->xml_struct);
            return 
true;
        } else {
            return 
false;
        }
    }
    
    public function 
readXmlFromDB() {
        
$sql "SELECT file_content FROM config_files WHERE file_name = '".$this->xml_file."'";
        
$this->db->sqlQuery($sql);
        
$rss $this->db->getRssData();
        if ( 
is_object($rss) ) {
            
$this->xml_struct = @unserialize($rss->file_content) ? unserialize($rss->file_content) : array();
        } else {
            return 
false;
        }
    }
    
    
//i couldnt find a good reason to preserve the cdata, so, i delete it :)
    
protected function xmlRemoveCdata($struct) {
        
$new_struct = array();
        foreach ( 
$struct as $index => $props ) {
            if ( 
$props['type'] != "cdata" ) {
                
$new_struct[] = $props;
            }
        }
        return 
$new_struct;
    }
    
    
//create the multidimensional array depending on the values returned by the php xml parser (recursive function)
    
protected function createXmlStruct($xml_level_tags,&$xml_struct) {
        foreach ( 
$xml_level_tags as $index => $keys ) {
            
$global_ix $keys['global_index'];
            
$props     $keys['values'];
            
$tag_type  $props['type'];
            
$tag       $props['tag'];
            
$tag_value = isset($props['value'])      ? $props['value']      : "";
            
$tag_atts  = isset($props['attributes']) ? $props['attributes'] : array();
            
$tag_level $props['level'];
            switch ( 
$tag_type ) {
                
                case 
'cdata':
                    continue;
                    break;
                    
                case 
'open':
                    if ( !
array_key_exists($tag,$xml_struct) ) {
                        
$xml_struct[$tag] = array();
                    }
                    
$next count($xml_struct[$tag]);
                    
$xml_struct[$tag][$next]               = array();
                    
$xml_struct[$tag][$next]['sub-tags']   = array();
                    
$xml_struct[$tag][$next]['attributes'] = array();
                    
$xml_struct[$tag][$next]['value']      = $tag_value;
                    
$xml_struct[$tag][$next]['type']       = 'open';
                    
$xml_struct[$tag][$next]['level']      = $tag_level;
                    foreach ( 
$tag_atts as $attribute => $att_value ) {
                        if ( !
array_key_exists($attribute,$xml_struct[$tag][$next]['attributes']) ) {
                            
$xml_struct[$tag][$next]['attributes'][$attribute] = array();
                        }
                        
$xml_struct[$tag][$next]['attributes'][$attribute][] = $att_value;
                    }
                    
$tag_children = array();
                    
$tag_children $this->getTagChildren($global_ix);
                    
$this->createXmlStruct($tag_children,$xml_struct[$tag][$next]['sub-tags']);
                    break;
                    
                case 
'close':
                    continue;
                    break;
                
                case 
'complete':
                    if ( !
array_key_exists($tag,$xml_struct) ) {
                        
$xml_struct[$tag] = array();
                    }
                    
$next count($xml_struct[$tag]);
                    
$xml_struct[$tag][$next]               = array();
                    
$xml_struct[$tag][$next]['sub-tags']   = array();
                    
$xml_struct[$tag][$next]['attributes'] = array();
                    
$xml_struct[$tag][$next]['value']      = $tag_value;
                    
$xml_struct[$tag][$next]['type']       = 'complete';
                    
$xml_struct[$tag][$next]['level']      = $tag_level;
                    foreach ( 
$tag_atts as $attribute => $att_value ) {
                        if ( !
array_key_exists($attribute,$xml_struct[$tag][$next]['attributes']) ) {
                            
$xml_struct[$tag][$next]['attributes'][$attribute] = array();
                        }
                        
$xml_struct[$tag][$next]['attributes'][$attribute][] = $att_value;
                    }
                    break;
                
                default:
                    break;
            }
        }
    }
    
    
//creates xml data from an xml struct
    
public function createXml(&$xmldata NULL,$tags NULL,&$pending_tags = array(),$default_level 1) {
        if ( 
$xmldata === NULL ) {
            
$xmldata = &$this->xml_data;
        }
        
$tags    $tags  === NULL   $this->xml_struct $tags;
        foreach ( 
$tags as $tag_name => $clon_tags ) {
            foreach ( 
$clon_tags as $clon_index => $clon_props ) {
                
$sub_tags   $clon_props['sub-tags'];
                
$attributes $clon_props['attributes'];
                
$type       $clon_props['type'];
                
$level      $clon_props['level'];
                
$value      $clon_props['value'];
                
$atts       "";
                
$tab        str_repeat("\t",$level);
                
$top        count($pending_tags);
                for ( 
$i $top$i >=$level$i-- ) {
                    
$levelname  "level_".$i;
                    if ( 
array_key_exists($levelname,$pending_tags) ) {
                        
$xmldata .=  $pending_tags[$levelname];
                        unset(
$pending_tags[$levelname]);
                    }
                }
                
$levelname "level_".$level;
                foreach ( 
$attributes as $att_name => $att_clons ) {
                    foreach ( 
$att_clons as $index_clon => $att_value ) {
                        
$atts .= $att_name.'="'.$att_value.'" ';
                    }
                }
                
$atts = empty($attributes) ? "" " ".$atts;
                
$atts rtrim($atts);
                if ( 
$type == 'open' ) {
                    
$xmldata .= $tab."<".$tag_name.$atts.">".$value."\n";
                    
$pending_tags[$levelname] = $tab."</".$tag_name.">"."\n";
                } else {
                    if ( 
$value == "" ) {
                        
$xmldata .= $tab."<".$tag_name.$atts."/>"."\n";
                    } else {
                        
$xmldata .= $tab."<".$tag_name.$atts.">".$value."</".$tag_name.">"."\n";
                    }
                }
                
$this->createXml($xmldata,$sub_tags,&$pending_tags,$default_level+1);
            }
        }
        
$default_level_name 'level_'.$default_level;
        if ( isset(
$pending_tags[$default_level_name]) ) {
            
$xmldata .= $pending_tags[$default_level_name];
            unset(
$pending_tags[$default_level_name]);
        }
    }
    
    
//saves the data to the file and database
    
public function saveXml($file "") {
        
$file $file == "" $this->xml_file $file;
        
$fp      fopen($file,'w');
        
$bytes   fwrite($fp,$this->xml_data);
        
$file    $this->xml_file;
        
$content serialize($this->xml_struct);
        
$content str_replace('\'',"\"",$content);
        
$sql     "UPDATE config_files SET file_content = '".$content."' WHERE file_name = '".$file."'";
        
$this->db->sqlQuery($sql);
        
fclose($fp);
        if ( 
$bytes !== false) {
            return 
true;
        } else {
            return 
false;
        }
    }
    
    
//get the XML tags in certain level of deepness
    
protected function getXmlLevelTags($level) {
        
$level_tags = array();
        
$cnt        0;
        foreach ( 
$this->xml_values as $index => $props ) {
            if ( 
$props['level'] == $level ) {
                
$level_tags[$cnt]['values']       = $props;
                
$level_tags[$cnt]['global_index'] = $index;
                
$cnt++;
            }
        }
        return 
$level_tags;
    }
    
    
//get the children tags of some other tag
    
protected function getTagChildren($index) {
        
$children     = array();
        
$tag          $this->xml_values[$index];
        
$level        $tag['level'];
        
$target_level $level 1;
        
$index++;
        
$cnt          0;
        while ( 
$this->xml_values[$index]['level'] > $level ) {
            if ( 
$target_level == $this->xml_values[$index]['level'] ) {
                
$children[$cnt]['global_index'] = $index;
                
$children[$cnt]['values']       = $this->xml_values[$index];
                
$cnt++;
            }
            
$index++;
        }
        return 
$children;
    }
    
    
//free the parser
    
public function __destruct() {
        
xml_parser_free($this->xml_parser);
        return 
true;
    }
    

?>
saludos
  #3 (permalink)  
Antiguo 06/05/2005, 11:55
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
sism82 ..

Estaría bueno que coloques un ejemplo de uso (recuerda que no todo el mundo se "maneja" con classes) .. También hacer mención sobre que versión de PHP funciona (pues el tratamiento que "se vé" es para PHP 5.x? no? ... Si hay algún detalle que tener encuenta para usarlo en PHP 4.x sería bueno que lo menciones; tal vez quitar "public" .. "private" y alguna cosa más si corresponde).

Un saludo,
  #4 (permalink)  
Antiguo 06/05/2005, 14:09
Avatar de alexjnm  
Fecha de Ingreso: octubre-2004
Ubicación: cuba
Mensajes: 218
Antigüedad: 19 años, 5 meses
Puntos: 1
gracias

gracias cluster por que ha la verdad que no sabia que haer con ese codigo
no tenia ni idea de que era eso, el problkema es que nunca e trabajado con php y xml, disculpa pero tendras un pequeño ejemplo de como usarlo para ver mas o menos como se emplea.

gracias y disculpa las molestias
alex
__________________
__________________________________________________ _________
A beses el camino mas largo es la solución mas eficaz :)
  #5 (permalink)  
Antiguo 06/05/2005, 15:35
 
Fecha de Ingreso: marzo-2003
Mensajes: 119
Antigüedad: 21 años
Puntos: 0
aquí tienes algo que a mi me funciona.

parser.php:
Código PHP:
<?php
// {{{ toString()
/**
* This method converts a file to a string. It returns an Error object if it is unable to open the file.
*
* @param    fileName String. The name of the file to convert.
*
* @return    String
* @author  simgar
*/

function & toString$fileName )
{
    if (
$content_array file($fileName))
    {
        return 
implode(""$content_array);
    }
    else
    {
        
// Error
        
return false;
    }
}
// }}}

// {{{ xmlFileToArray()
/**
* This static method converts an xml file to an associative array
* duplicating the xml file structure.
*
* @param    $fileName. String. The name of the xml file to convert.
*             This method returns an Error object if this file does not
*             exist or is invalid.
* @param    $includeTopTag. booleal. Whether or not the topmost xml tag
*             should be included in the array. The default value for this is false.
* @param    $lowerCaseTags. boolean. Whether or not tags should be
*            set to lower case. Default value for this parameter is true.
* @access    public static
* @return    Associative Array
* @author    Jason Read <[email protected]>
*/
function & xmlFileToArray($fileName$includeTopTag false$lowerCaseTags true)
{
    
// Definition file not found
    
if (!file_exists($fileName))
    {
        
// Error
        
return false;
    }
    
$p xml_parser_create();
    
xml_parse_into_struct($p,toString($fileName),$vals,$index);
    
xml_parser_free($p);
    
$xml = array();
    
$levels = array();
    
$multipleData = array();
    
$prevTag "";
    
$currTag "";
    
$topTag false;
    foreach (
$vals as $val)
    {
        
// Open tag
        
if ($val["type"] == "open")
        {
            if (!
_xmlFileToArrayOpen($topTag$includeTopTag$val$lowerCaseTags,
                                           
$levels$prevTag$multipleData$xml))
            {
                continue;
            }
        }
        
// Close tag
        
else if ($val["type"] == "close")
        {
            if (!
_xmlFileToArrayClose($topTag$includeTopTag$val$lowerCaseTags,
                                            
$levels$prevTag$multipleData$xml))
            {
                continue;
            }
        }
        
// Data tag
        
else if ($val["type"] == "complete" && isset($val["value"]))
        {
            
$loc =& $xml;
            foreach (
$levels as $level)
            {
                
$temp =& $loc[str_replace(":arr#"""$level)];
                
$loc =& $temp;
            }
            
$tag $val["tag"];
            if (
$lowerCaseTags)
            {
                
$tag strtolower($val["tag"]);
            }
            
$loc[$tag] = str_replace("\\n""\n"$val["value"]);
        }
        
// Tag without data
        
else if ($val["type"] == "complete")
        {
            
_xmlFileToArrayOpen($topTag$includeTopTag$val$lowerCaseTags,
                                      
$levels$prevTag$multipleData$xml);
            
_xmlFileToArrayClose($topTag$includeTopTag$val$lowerCaseTags,
                                      
$levels$prevTag$multipleData$xml);
        }
    }
    return 
$xml;
}
// }}}

// {{{ _xmlFileToArrayOpen()
/**
* Private support function for xmlFileToArray. Handles an xml OPEN tag.
*
* @param    $topTag. String. xmlFileToArray topTag variable
* @param    $includeTopTag. boolean. xmlFileToArray includeTopTag variable
* @param    $val. String[]. xmlFileToArray val variable
* @param    $currTag. String. xmlFileToArray currTag variable
* @param    $lowerCaseTags. boolean. xmlFileToArray lowerCaseTags variable
* @param    $levels. String[]. xmlFileToArray levels variable
* @param    $prevTag. String. xmlFileToArray prevTag variable
* @param    $multipleData. boolean. xmlFileToArray multipleData variable
* @param    $xml. String[]. xmlFileToArray xml variable
* @access    private static
* @return    boolean
* @author    Jason Read <[email protected]>
*/
function _xmlFileToArrayOpen(& $topTag, & $includeTopTag, & $val, & $lowerCaseTags,
                             & 
$levels, & $prevTag, & $multipleData, & $xml)
{
    
// don't include top tag
    
if (!$topTag && !$includeTopTag)
    {
        
$topTag $val["tag"];
        return 
false;
    }
    
$currTag $val["tag"];
    if (
$lowerCaseTags)
    {
        
$currTag strtolower($val["tag"]);
    }
    
$levels[] = $currTag;
    
    
// Multiple items w/ same name. Convert to array.
    
if ($prevTag === $currTag)
    {
        if (!
array_key_exists($currTag$multipleData) ||
            !
$multipleData[$currTag]["multiple"])
        {
            
$loc =& $xml;
            foreach (
$levels as $level)
            {
                
$temp =& $loc[$level];
                
$loc =& $temp;
            }
            
$loc = array($loc);
            
$multipleData[$currTag]["multiple"] = true;
            
$multipleData[$currTag]["multiple_count"] = 0;
        }
        
$multipleData[$currTag]["popped"] = false;
        
$levels[] = ":arr#" . ++$multipleData[$currTag]["multiple_count"];
    }
    else
    {
        
$multipleData[$currTag]["multiple"] = false;
    }
    
    
// Add attributes array
    
if (array_key_exists("attributes"$val))
    {
        
$loc =& $xml;
        foreach (
$levels as $level)
        {
            
$temp =& $loc[str_replace(":arr#"""$level)];
            
$loc =& $temp;
        }
        
$keys array_keys($val["attributes"]);
        foreach (
$keys as $key)
        {
            
$tag $key;
            if (
$lowerCaseTags)
            {
                
$tag strtolower($tag);
            }
            
$loc["attributes"][$tag] = & $val["attributes"][$key];
        }
    }
    return 
true;
}
// }}}

// {{{ _xmlFileToArrayClose()
/**
* Private support function for xmlFileToArray. Handles an xml OPEN tag.
*
* @param    $topTag. String. xmlFileToArray topTag variable
* @param    $includeTopTag. boolean. xmlFileToArray includeTopTag variable
* @param    $val. String[]. xmlFileToArray val variable
* @param    $currTag. String. xmlFileToArray currTag variable
* @param    $lowerCaseTags. boolean. xmlFileToArray lowerCaseTags variable
* @param    $levels. String[]. xmlFileToArray levels variable
* @param    $prevTag. String. xmlFileToArray prevTag variable
* @param    $multipleData. boolean. xmlFileToArray multipleData variable
* @param    $xml. String[]. xmlFileToArray xml variable
* @access    private static
* @return    boolean
* @author    Jason Read <[email protected]>
*/
function _xmlFileToArrayClose(& $topTag, & $includeTopTag, & $val, & $lowerCaseTags,
                              & 
$levels, & $prevTag, & $multipleData, & $xml)
{
    
// don't include top tag
    
if ($topTag && !$includeTopTag && $val["tag"] == $topTag)
    {
        return 
false;
    }
    if (
$multipleData[$currTag]["multiple"])
    {
        
$tkeys array_reverse(array_keys($multipleData));
        foreach (
$tkeys as $tkey)
        {
            if (
$multipleData[$tkey]["multiple"] && !$multipleData[$tkey]["popped"])
            {
                
array_pop($levels);
                
$multipleData[$tkey]["popped"] = true;
                break;
            }
            else if (!
$multipleData[$tkey]["multiple"])
            {
                break;
            }
        }
    }
    
$prevTag array_pop($levels);
    if (
strpos($prevTag"arr#"))
    {
        
$prevTag array_pop($levels);
    }
    return 
true;
}
// }}}
?>
en tu archivo:
Código PHP:
include("parser.php");
$array=xmlFileToArray("nombredelarchivo.xml"); 
con print_r($array) puedes ver la estructura del array para poder extraer la información que te interese
  #6 (permalink)  
Antiguo 06/05/2005, 15:48
O_O
 
Fecha de Ingreso: enero-2002
Ubicación: Santiago - Chile
Mensajes: 34.417
Antigüedad: 22 años, 3 meses
Puntos: 129
Cita:
Iniciado por alexjnm
gracias cluster por que ha la verdad que no sabia que haer con ese codigo
no tenia ni idea de que era eso, el problkema es que nunca e trabajado con php y xml, disculpa pero tendras un pequeño ejemplo de como usarlo para ver mas o menos como se emplea.

gracias y disculpa las molestias
alex
El código es de sism82 .. justamente le pedía a el que expusiera un ejemplo de uso.

Un saludo,
  #7 (permalink)  
Antiguo 06/05/2005, 17:00
Avatar de sism82  
Fecha de Ingreso: octubre-2003
Ubicación: Guadalajara
Mensajes: 865
Antigüedad: 20 años, 5 meses
Puntos: 1
atendiendo a la justa petición de cluster.......
código modificado para php4 y sin dependencia de base de datos
Código PHP:
<?php
/********************* Xml_Config  ******************/
/*
this class uses the php xml parser to construct a multidimensional array with the values of an XML file
*/
class XmlConfig {
    
     
$xml_parser NULL
     
$xml_values = array();
     
$xml_indexs = array();
     
$xml_struct = array();
     
$xml_data   "";
     
$xml_file   "";
    
    function 
XmlConfig($file "") {
        
$this->xml_parser           xml_parser_create();
        if ( 
$file != "" ) {
            
$this->setXmlFile($file);
            return 
$this->readXml();
        } else {
            return 
true;
        }
    }
    
    function 
setXmlFile($file) {
        
$this->xml_file $file;
        return 
true;
    }
    
    function 
readXml() {
        if ( 
is_file($this->xml_file) && is_readable($this->xml_file) ) {
            
$data file_get_contents($this->xml_file);
            
xml_parse_into_struct($this->xml_parser,$data,$this->xml_values,$this->xml_indexs);
            
$this->xml_values $this->xmlRemoveCdata($this->xml_values);
            
$xml_level_tags $this->getXmlLevelTags(1);
            
$this->createXmlStruct($xml_level_tags,$this->xml_struct);
            return 
true;
        } else {
            return 
false;
        }
    }
    
    
//i couldnt find a good reason to preserve the cdata, so, i delete it :)
     
function xmlRemoveCdata($struct) {
        
$new_struct = array();
        foreach ( 
$struct as $index => $props ) {
            if ( 
$props['type'] != "cdata" ) {
                
$new_struct[] = $props;
            }
        }
        return 
$new_struct;
    }
    
    
//create the multidimensional array depending on the values returned by the php xml parser (recursive function)
     
function createXmlStruct($xml_level_tags,&$xml_struct) {
        foreach ( 
$xml_level_tags as $index => $keys ) {
            
$global_ix $keys['global_index'];
            
$props     $keys['values'];
            
$tag_type  $props['type'];
            
$tag       $props['tag'];
            
$tag_value = isset($props['value'])      ? $props['value']      : "";
            
$tag_atts  = isset($props['attributes']) ? $props['attributes'] : array();
            
$tag_level $props['level'];
            switch ( 
$tag_type ) {
                
                case 
'cdata':
                    continue;
                    break;
                    
                case 
'open':
                    if ( !
array_key_exists($tag,$xml_struct) ) {
                        
$xml_struct[$tag] = array();
                    }
                    
$next count($xml_struct[$tag]);
                    
$xml_struct[$tag][$next]               = array();
                    
$xml_struct[$tag][$next]['sub-tags']   = array();
                    
$xml_struct[$tag][$next]['attributes'] = array();
                    
$xml_struct[$tag][$next]['value']      = $tag_value;
                    
$xml_struct[$tag][$next]['type']       = 'open';
                    
$xml_struct[$tag][$next]['level']      = $tag_level;
                    foreach ( 
$tag_atts as $attribute => $att_value ) {
                        if ( !
array_key_exists($attribute,$xml_struct[$tag][$next]['attributes']) ) {
                            
$xml_struct[$tag][$next]['attributes'][$attribute] = array();
                        }
                        
$xml_struct[$tag][$next]['attributes'][$attribute][] = $att_value;
                    }
                    
$tag_children = array();
                    
$tag_children $this->getTagChildren($global_ix);
                    
$this->createXmlStruct($tag_children,$xml_struct[$tag][$next]['sub-tags']);
                    break;
                    
                case 
'close':
                    continue;
                    break;
                
                case 
'complete':
                    if ( !
array_key_exists($tag,$xml_struct) ) {
                        
$xml_struct[$tag] = array();
                    }
                    
$next count($xml_struct[$tag]);
                    
$xml_struct[$tag][$next]               = array();
                    
$xml_struct[$tag][$next]['sub-tags']   = array();
                    
$xml_struct[$tag][$next]['attributes'] = array();
                    
$xml_struct[$tag][$next]['value']      = $tag_value;
                    
$xml_struct[$tag][$next]['type']       = 'complete';
                    
$xml_struct[$tag][$next]['level']      = $tag_level;
                    foreach ( 
$tag_atts as $attribute => $att_value ) {
                        if ( !
array_key_exists($attribute,$xml_struct[$tag][$next]['attributes']) ) {
                            
$xml_struct[$tag][$next]['attributes'][$attribute] = array();
                        }
                        
$xml_struct[$tag][$next]['attributes'][$attribute][] = $att_value;
                    }
                    break;
                
                default:
                    break;
            }
        }
    }
    
    
//creates xml data from an xml struct
     
function createXml(&$xmldata NULL$tags NULL, &$pending_tags = array(), $default_level 1) {
        if ( 
$xmldata === NULL ) {
            
$xmldata = &$this->xml_data;
        }
        
$tags    $tags  === NULL   $this->xml_struct $tags;
        foreach ( 
$tags as $tag_name => $clon_tags ) {
            foreach ( 
$clon_tags as $clon_index => $clon_props ) {
                
$sub_tags   $clon_props['sub-tags'];
                
$attributes $clon_props['attributes'];
                
$type       $clon_props['type'];
                
$level      $clon_props['level'];
                
$value      $clon_props['value'];
                
$atts       "";
                
$tab        str_repeat("\t",$level);
                
$top        count($pending_tags);
                for ( 
$i $top$i >=$level$i-- ) {
                    
$levelname  "level_".$i;
                    if ( 
array_key_exists($levelname,$pending_tags) ) {
                        
$xmldata .=  $pending_tags[$levelname];
                        unset(
$pending_tags[$levelname]);
                    }
                }
                
$levelname "level_".$level;
                foreach ( 
$attributes as $att_name => $att_clons ) {
                    foreach ( 
$att_clons as $index_clon => $att_value ) {
                        
$atts .= $att_name.'="'.$att_value.'" ';
                    }
                }
                
$atts = empty($attributes) ? "" " ".$atts;
                
$atts rtrim($atts);
                if ( 
$type == 'open' ) {
                    
$xmldata .= $tab."<".$tag_name.$atts.">".$value."\n";
                    
$pending_tags[$levelname] = $tab."</".$tag_name.">"."\n";
                } else {
                    if ( 
$value == "" ) {
                        
$xmldata .= $tab."<".$tag_name.$atts."/>"."\n";
                    } else {
                        
$xmldata .= $tab."<".$tag_name.$atts.">".$value."</".$tag_name.">"."\n";
                    }
                }
                
$this->createXml($xmldata,$sub_tags,$pending_tags,$default_level+1);
            }
        }
        
$default_level_name 'level_'.$default_level;
        if ( isset(
$pending_tags[$default_level_name]) ) {
            
$xmldata .= $pending_tags[$default_level_name];
            unset(
$pending_tags[$default_level_name]);
        }
    }
    
    
//saves the data to the file and database
     
function saveXml($file "") {
        
$file $file == "" $this->xml_file $file;
        
$fp      fopen($file,'w');
        
$bytes   fwrite($fp,$this->xml_data);
        
$file    $this->xml_file;
        
fclose($fp);
        if ( 
$bytes !== false) {
            return 
true;
        } else {
            return 
false;
        }
    }
    
    
//get the XML tags in certain level of deepness
     
function getXmlLevelTags($level) {
        
$level_tags = array();
        
$cnt        0;
        foreach ( 
$this->xml_values as $index => $props ) {
            if ( 
$props['level'] == $level ) {
                
$level_tags[$cnt]['values']       = $props;
                
$level_tags[$cnt]['global_index'] = $index;
                
$cnt++;
            }
        }
        return 
$level_tags;
    }
    
    
//get the children tags of some other tag
     
function getTagChildren($index) {
        
$children     = array();
        
$tag          $this->xml_values[$index];
        
$level        $tag['level'];
        
$target_level $level 1;
        
$index++;
        
$cnt          0;
        while ( 
$this->xml_values[$index]['level'] > $level ) {
            if ( 
$target_level == $this->xml_values[$index]['level'] ) {
                
$children[$cnt]['global_index'] = $index;
                
$children[$cnt]['values']       = $this->xml_values[$index];
                
$cnt++;
            }
            
$index++;
        }
        return 
$children;
    }    
    


//probando
$xml = new XmlConfig();
$xml->setXmlFile('helloworld.xml');
$xml->readXml();
echo 
'<pre>';
var_dump($xml->xml_struct);
echo 
'</pre>';
?>
Te dejo nuevamente el código para que no dependa de php5 ni de la base de datos (no hay respaldo del archivo en base de datos)
Basicamente lee el archivo XML y lo convierte a una estructura de PHP.

Los campos de la estructura PHP son:

- value : contenido de la etiqueta XML

- sub-tags: (array) todas las etiquetas anidadas, cada etiqueta es en si misma una estructura de php igual a esta, es decir, cada elemento de este arreglo de subtags, tiene a su vez otro elemento subtags para contener mas etiquetas anidadas.

- attributes: (array) Propiedades de la etiqueta XML

- type: (string)si la etiqueta es de apertura, o unica (open, complete)

- level: (int) Nivel de anidacion

Estoy seguro que si haces la prueba y estudias un poco el código entenderas que esta información es valiosa para manipular los datos XML desde un script php.

EL método createXml hace la conversión inversa que readXml, de la estructura php pasa a XML listo para er guardado con el método saveXml().

si indicas cual es el objetivo final de querer usar ese html tal vez se te pueda ayudar un poco más,

un saludo
  #8 (permalink)  
Antiguo 07/05/2005, 06:27
Avatar de alexjnm  
Fecha de Ingreso: octubre-2004
Ubicación: cuba
Mensajes: 218
Antigüedad: 19 años, 5 meses
Puntos: 1
gracias a todos

gracias a todos,
sims82 el codigo que me diste me da error en la linea 8 nose por que sera estoy usando php 4.3.4. gracias de todas formas y disculpa las molestias que cause.
lo que quiero es almasenar el xml en un array para despues poder sacarlo y ponerlo donde mas me plasca. no se si me ago entender.

es desir $array("sample.xml");
y despues poder decir echo $array[1]; nose algo asi disculpen si estoy poniendo halgo que noba o si estoy equivocado pero es que nunca e trabajado con xml y php y nose la filosofia de como trabajarlo.
espero haberme echo entender
saludos alex
__________________
__________________________________________________ _________
A beses el camino mas largo es la solución mas eficaz :)

Última edición por alexjnm; 07/05/2005 a las 06:33
  #9 (permalink)  
Antiguo 08/05/2005, 17:39
Avatar de sism82  
Fecha de Ingreso: octubre-2003
Ubicación: Guadalajara
Mensajes: 865
Antigüedad: 20 años, 5 meses
Puntos: 1
y corregiste el error? que mas necesitas entonces? el error debe ser algun caracter que teclee mal a la hora de modificarlo para php4, nada mas.

por favor se mas explicito cuando escribas, si dices que da un error, entonces aclara que error etc etc
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 02:41.