IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

Fichier XML vers tableau associatif [PHP 5.6]


Sujet :

Langage PHP

  1. #1
    Membre régulier Avatar de hucste
    Homme Profil pro
    IT en Arrêt Chronique de Sans-T !
    Inscrit en
    Juin 2016
    Messages
    78
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Lot et Garonne (Aquitaine)

    Informations professionnelles :
    Activité : IT en Arrêt Chronique de Sans-T !

    Informations forums :
    Inscription : Juin 2016
    Messages : 78
    Points : 113
    Points
    113
    Par défaut Fichier XML vers tableau associatif
    Bonjour,

    Depuis quelques jours, je me casse les dents sur du code PHP pour extraire des données d'un fichier XML vers un tableau associatif PHP ...

    Ce que je souhaite arriver à obtenir est ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
     
    array(3) {
      ["zao"]=>
      array(4) {
        ["version"]=>
        string(5) "0.1.5"
        ["date"]=>
        string(35) "2015-08-26 20:15:43.912878767 +0200"
        ["name"]=>
        string(25) "Z -> Another Object (web)"
        ["url"]=>
        string(32) "https://framagit.org/hucste/ZAO/"
      }
      ["h5bp"]=>
      array(3) {
        ["name"]=>
        string(16) "HTML5BoilerPlate"
        ["url"]=>
        string(29) "https://html5boilerplate.com/"
        ["version"]=>
        string(5) "5.2.0"
      }
      ["bootstrap"]=>
      array(4) {
        ["name"]=>
        string(9) "Bootstrap"
        ["url"]=>
        string(24) "https://getbootstrap.com"
        ["version"]=>
        string(5) "3.3.6"
        ["integrity"]=>
          array(3) {
            ["css"] => string() "sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
            ["js"] => string() "sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
            ["theme"] => string() "sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
          }
      }
    Mon code PHP actuel :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    if( $this->action == 'version' ) {
     
                    $elements = $dom->getElementsByTagName( 'datas' );
     
                    $version = $this->xml_to_array($elements);
     
                    if(!empty($version)) $this->version = $version;
     
                    unset($elements, $version);
                }
    La méthode 'xml_to_array()' actuelle est ainsi :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
     
    private function xml_to_array($elements) {
     
            $array = array();
     
            foreach($elements as $element) {
     
                if($element->childNodes->length != null) {
     
                    foreach($element->childNodes as $idx) {
     
                        $idx_name = filter_var(strip_tags($idx->nodeName), FILTER_SANITIZE_STRING);
                        if( $idx_name != '#text') {
                            $array[$idx_name] = array();
     
                            if($idx_name == "zao" && $idx->getAttribute('version')) $array[$idx_name]['version'] = $idx->getAttribute('version');
     
                            if($idx->childNodes->length != null) {
     
                                foreach($idx->childNodes as $info) {
     
                                    if($info->nodeName != '#text') {
                                        $info_name = filter_var(strip_tags($info->nodeName), FILTER_SANITIZE_STRING);
                                        $info_value = filter_var(strip_tags($info->nodeValue), FILTER_SANITIZE_STRING);
     
                                        $array[$idx_name][$info_name] = $info_value;
     
                                        unset($info_name, $info_value);
                                    }
     
                                }
                                unset($info);
                            }
                        }
                        unset($idx_name);
                    }
                    unset($idx);
                }
            }
            unset($element);
     
            if(!empty($array)) { return $array; unset($array); }
     
        }
    Bref, dans ce contexte, j'ai essayé de modifier le code de la méthode 'xml_to_array' pour qu'elle soit plus "dynamique" et puisse parcourir l'arbre xml de mon fichier ... mais quelque soit les essais, je n'arrive pas à descendre au niveau des noeuds enfants du noeud integrity ...

    Il y a quelque chose que je ne suis pas arrivé à comprendre ...
    Merci d'avance pour l'aide

  2. #2
    Expert éminent sénior
    Avatar de rawsrc
    Homme Profil pro
    Dev indep
    Inscrit en
    Mars 2004
    Messages
    6 142
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : France, Bouches du Rhône (Provence Alpes Côte d'Azur)

    Informations professionnelles :
    Activité : Dev indep

    Informations forums :
    Inscription : Mars 2004
    Messages : 6 142
    Points : 16 545
    Points
    16 545
    Billets dans le blog
    12
    Par défaut
    Salut,

    bon, je vais te sécher mais la transformation d'un XML en tableau tient en une seule ligne :
    attention roulement de tambour :
    Code php : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    <?php 
     
    $xml = <<<'xml'
    <?xml version="1.0" encoding="UTF-8"?>
    <page id="version">
    <title>ZAO Informations Versions</title>
    <author>Stéphane HUC</author>
    <description>ZAO::Informations de versions</description>
    <datas>
        <zao version="0.1.5">
            <date timestamp="1440612943">2015-08-26 20:15:43.912878767 +0200</date>
            <name>Z -> Another Object (web)</name>
            <url>https://framagit.org/hucste/ZAO/</url>
        </zao>
        <h5bp>
            <name>HTML5BoilerPlate</name>
            <url>https://html5boilerplate.com/</url>
            <version>5.2.0</version>
        </h5bp>
        <bootstrap>
            <name>Bootstrap</name>
            <url>https://getbootstrap.com</url>
            <version>3.3.6</version>
            <integrity>
                <css>sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7</css>
                <js>sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS</js>
                <theme>sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r</theme>
            </integrity>
        </bootstrap>
    </datas>
    </page>
    xml;
     
    $sxml  = simplexml_load_string($xml);
    $array = (array)$sxml;
    Après, je te laisse découper le tableau à ta guise

  3. #3
    Membre régulier Avatar de hucste
    Homme Profil pro
    IT en Arrêt Chronique de Sans-T !
    Inscrit en
    Juin 2016
    Messages
    78
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Lot et Garonne (Aquitaine)

    Informations professionnelles :
    Activité : IT en Arrêt Chronique de Sans-T !

    Informations forums :
    Inscription : Juin 2016
    Messages : 78
    Points : 113
    Points
    113
    Par défaut
    @rawsrc: sincérement, je te remercie ... tu m'a mis sur la voie ; tout n'as pas été simple, mais je suis arrivé à une solution intéressante, et sans passer par une déclaration array :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
            $xml = simplexml_load_file($this->file);
     
            if( strcmp( $xml->attributes()->id, $this->action ) == 0 ) $bool = true;
     
            if( $bool ) {
     
                $this->title = $this->builderDatas( (string) $xml->title );
                $this->description = $this->builderDatas( (string) $xml->description );
     
                if( $this->action == 'version' ) {
     
                    $this->version = $xml->datas;
     
                }
                else {
     
                    $datas = str_replace(array('<datas>', '</datas>'), '', $xml->datas->asXML());
     
                    $this->datas = $this->builderDatas( $datas );
     
                    $h1 = str_replace(array('<h1>', '</h1>'), '', $xml->datas->h1->asXML());
                    $this->head1 = $this->builderDatas( $h1 );
                }
     
            }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 21
    Dernier message: 06/02/2007, 14h05
  2. [JDOM] Déplacer un sous arbre d'un fichier xml vers un autre
    Par LannionJava dans le forum Format d'échange (XML, JSON...)
    Réponses: 5
    Dernier message: 21/07/2006, 16h51
  3. Réponses: 1
    Dernier message: 28/04/2006, 17h17
  4. Importation d'un fichier xml vers une BD mysql avec php
    Par naima2005 dans le forum SQL Procédural
    Réponses: 1
    Dernier message: 28/04/2006, 16h23
  5. newbie : fichier xml vers html via command-line
    Par morti dans le forum XML/XSL et SOAP
    Réponses: 1
    Dernier message: 08/11/2005, 08h34

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo