New question

Question:

Date: 18-05-2018 10:07:36 (In Spanish)

Array PHP a XML [Resolved]

Buenos dias quisiera saber si alguno de ustedes a podido convertir un arreglo de php en xml, cual es la mejor forma de hacerlo, tengo esta clase pero no me convence del todo.
class ArrayToXML
{
    private $version;
    private $encoding;

    /**
     * Construct ArrayToXML object with selected version and encoding
     *
     * for available values check XmlWriter docs http://www.php.net/manual/en/function.xmlwriter-start-document.php
     * @param string $xmlVersion XML Version, default 1.0
     * @param string $xmlEncoding XML Encoding, default UTF-8
     */
    public function __construct($xmlVersion = '1.0', $xmlEncoding = 'UTF-8')
    {
        $this->version = $xmlVersion;
        $this->encoding = $xmlEncoding;
    }

    /**
     * Build an XML Data Set
     *
     * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
     * @param string $startElement Root Opening Tag, default data
     * @return string XML String containing values
     * @return mixed Boolean false on failure, string XML result on success
     */
    public function buildXML($data, $startElement = 'data')
    {
        if (!is_array($data)) {
            $err = 'Invalid variable type supplied, expected array not found on line ' . __LINE__ . ' in Class: ' . __CLASS__ . ' Method: ' . __METHOD__;
            trigger_error($err);
            return false; //return false error occurred
        }
        $xml = new XmlWriter();
        $xml->openMemory();
        $xml->startDocument($this->version, $this->encoding);
        $xml->startElement($startElement);

        $data = $this->writeAttr($xml, $data);
        $this->writeEl($xml, $data);

        $xml->endElement(); //write end element
        //returns the XML results
        return $xml->outputMemory(true);
    }

    /**
     * Write keys in $data prefixed with @ as XML attributes, if $data is an array.
     * When an @ prefixed key is found, a '%' key is expected to indicate the element itself,
     * and '#' prefixed key indicates CDATA content
     *
     * @param XMLWriter $xml object
     * @param array $data with attributes filtered out
     * @return array $data | $nonAttributes
     */
    protected function writeAttr(XMLWriter $xml, $data)
    {
        if (is_array($data)) {
            $nonAttributes = array();
            foreach ($data as $key => $val) {
                //handle an attribute with elements
                if ($key[0] == '@') {
                    $xml->writeAttribute(substr($key, 1), $val);
                } else if ($key[0] == '%') {
                    if (is_array($val)) $nonAttributes = $val;
                    else $xml->text($val);
                } elseif ($key[0] == '#') {
                    if (is_array($val)) $nonAttributes = $val;
                    else {
                        $xml->startElement(substr($key, 1));
                        $xml->writeCData($val);
                        $xml->endElement();
                    }
                }else if($key[0] == "!"){
                    if (is_array($val)) $nonAttributes = $val;
                    else $xml->writeCData($val);
                } 
                //ignore normal elements
                else $nonAttributes[$key] = $val;
            }
            return $nonAttributes;
        } else return $data;
    }

    /**
     * Write XML as per Associative Array
     *
     * @param XMLWriter $xml object
     * @param array $data Associative Data Array
     */
    protected function writeEl(XMLWriter $xml, $data)
    {
        foreach ($data as $key => $value) {
            if (is_array($value) && !$this->isAssoc($value)) { //numeric array
                foreach ($value as $itemValue) {
                    if (is_array($itemValue)) {
                        $xml->startElement($key);
                        $itemValue = $this->writeAttr($xml, $itemValue);
                        $this->writeEl($xml, $itemValue);
                        $xml->endElement();
                    } else {
                        $itemValue = $this->writeAttr($xml, $itemValue);
                        $xml->writeElement($key, "$itemValue");
                    }
                }
            } else if (is_array($value)) { //associative array
                $xml->startElement($key);
                $value = $this->writeAttr($xml, $value);
                $this->writeEl($xml, $value);
                $xml->endElement();
            } else { //scalar
                $value = $this->writeAttr($xml, $value);
                $xml->writeElement($key, "$value");
            }
        }
    }

    /**
     * Check if array is associative with string based keys
     * FROM: http://stackoverflow.com/questions/173400/php-arrays-a-good-way-to-check-if-an-array-is-associative-or-sequential/4254008#4254008
     *
     * @param array $array Array to check
     * @return bool
     */
    protected function isAssoc($array)
    {
        return (bool)count(array_filter(array_keys($array), 'is_string'));
    }
}

Tags: PHP - Question - XML Votes: 3 - Answers: 5 - Views: 16 Share on: Google Facebook Twitter LinkedIn Link
 

Answers:

  • Date: 20-05-2018 17:47:22 Aquí hay un thread muy interesante en stackoverflow.
    Hay muchas soluciones (cuidado con la solución aceptada pues es de las peores LOL).

    Hay alguna razón por la que la clase que utilizas no te convence?
      Votes: 4 - Link answer
     
  • Date: 20-05-2018 20:06:52 Hola a todos

    Por lo que he podido ver en un vistazo al código, la implementación esta atada a XmlWriter, lo cual no es tan malo como se podría pensar, porque a partir de php 5.1.2 dejo de ser una extensión que debía instalarse para ser parte del código fuente de php, y por defecto esta habilitada.

    Si es verdad que si yo tendría que escribir una clase de este tipo usaría SimpleXML (por su facilidad de uso), aquí te dejo el enlace a la documentación oficial: Uso básico de SimpleXML

    Saludos y buen código!
      Votes: 3 - Link answer
     
  • Date: 22-05-2018 15:28:41 Hola

    Haré uso de un ejemplo de la web oficial de PHP que ha expuesto Fernando Uso básico de SimpleXML al cual lo he modificado para acceder de una manera simple a cada uno de los nodos del XML de ejemplo .

    print_r($peliculas) del ejemplo XML:


    El codigo que contiene el XML en la variable $xmlstr y la extracción de los datos de cada uno de los nodos.

    <?php
    // Uso de SimpleXML
    // Ejemplo de http://php.net/manual/es/simplexml.examples-basic.php
    
    $xmlstr = <<<XML
    <?xml version='1.0' standalone='yes'?>
    <peliculas>
     <pelicula>
      <titulo>PHP: Tras el Analilzador</titulo>
      <personajes>
       <personaje>
        <nombre>Srta. Programadora</nombre>
        <actor>Onlivia Actora</actor>
       </personaje>
       <personaje>
        <nombre>Sr. Programador</nombre>
        <actor>El Actor</actor>
       </personaje>
      </personajes>
      <argumento>
       Así que, este lenguaje. Es como, un lenguaje de programación. 
       ¿O es un lenguaje de script? 
       Lo descubrirás en esta intrigante y temible parodia de un documental.
      </argumento>
      <grandes-frases>
       <frase>PHP soluciona todos los problemas web</frase>
      </grandes-frases>
      <puntuacion tipo="votos">7</puntuacion>
      <puntuacion tipo="estrellas">5</puntuacion>
     </pelicula>
    </peliculas>
    XML;
    
    $peliculas = new SimpleXMLElement($xmlstr);
    header('Content-Type: text/html; charset=utf-8'); // codificación UTF-8 
    
    echo '<H1>Extracción de datos del XML.</H1><H2>Usando SimpleXML</H2><HR><BR>'.PHP_EOL; // PHP_EOL para el salto de linea en el codigo HTML
    echo '<strong>Titulo:</strong> '.$peliculas->pelicula[0]->titulo;
    echo '<BR><BR>';
    echo '<strong>Personajes:</strong><BR>';
    echo $peliculas->pelicula[0]->personajes->personaje[0]->nombre, ' interpretado por ',  $peliculas->pelicula[0]->personajes->personaje[0]->actor;
    echo '<BR>';
    echo $peliculas->pelicula[0]->personajes->personaje[1]->nombre, ' interpretado por ',  $peliculas->pelicula[0]->personajes->personaje[1]->actor;
    echo '<BR><BR>';
    echo '<strong>Argumento de la pelicula:</strong><BR>';
    echo $peliculas->pelicula[0]->argumento;
    echo '<BR><BR>';
    echo '<strong>Frase:</strong><BR>';
    echo $peliculas->pelicula->{'grandes-frases'}->frase;
    echo '<BR><BR>';
    echo '<strong>Puntuacion:</strong><BR>';
    echo 'Obtuvo ', $peliculas->pelicula->puntuacion[0], ' votos y ', $peliculas->pelicula->puntuacion[1], ' estrellas. ';
    




    Resultado:



    En la web oficial, el ejemplo es el más el indicado para acceder a cada nodo o elemento del XML, ya que en ciertos casos utiliza foreach(), switch() para acceder a algunos elementos puntuales como personajes y puntuación.

    Mi respuesta es meramente ilustrativa para dejar un ejemplo simple de como acceder a cada elemento del XML para quienes recién comienzan con XML.

    También pueden darle un vistazo a simplexml_load_string

    Documentación de SimpleXML.

    Espero que sea útil.

    Saludos
      Votes: 3 - Link answer
     
  • Date: 22-05-2018 15:48:40 Muchas gracias, indudablemte estaba más sencillo de lo que pensaba.   Votes: 0 - Link answer
     
  • Date: 22-05-2018 16:53:00 Como extra dejo un codigo de lectura de un documento XML en XML, Json, array.
    Creo que e
    <?php
    // Documento XML
    $xmlstr = <<<XML
    <?xml version='1.0' standalone='yes'?>
    <peliculas>
     <pelicula>
      <titulo>PHP: Tras el Analilzador</titulo>
      <personajes>
       <personaje>
        <nombre>Srta. Programadora</nombre>
        <actor>Onlivia Actora</actor>
       </personaje>
       <personaje>
        <nombre>Sr. Programador</nombre>
        <actor>El Actor</actor>
       </personaje>
      </personajes>
      <argumento>
       Así que, este lenguaje. Es como, un lenguaje de programación. 
       ¿O es un lenguaje de script? 
       Lo descubrirás en esta intrigante y temible parodia de un documental.
      </argumento>
      <grandes-frases>
       <frase>PHP soluciona todos los problemas web</frase>
      </grandes-frases>
      <puntuacion tipo="votos">7</puntuacion>
      <puntuacion tipo="estrellas">5</puntuacion>
     </pelicula>
    </peliculas>
    XML;
    
    // Lectura del XML
    
    $xml = new SimpleXMLElement($xmlstr);
    $json = json_encode($xml);
    $array = json_decode($json,TRUE);
    echo '<h2>Formato XML.</h2>';
    echo '<pre>';
    print_r($xml);
    echo '</pre>';
    echo '<hr>';
    echo '<h2>Formato JSON.</h2>';
    echo '<pre>';
    print_r($json);
    echo '</pre>';
    echo '<hr>';
    echo '<h2>Formato ARRAY.</h2>';
    echo '<pre>';
    print_r($array);
    echo '</pre>';
    




    Saludos
      Votes: 1 - Link answer
     
To actively participate in the community first must authenticate, enter the system.Sign In
 
frjcbbae garagebible.com