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 :

Convertir un fichier JSON dans un format XML en PHP avec DOM


Sujet :

Langage PHP

  1. #1
    Membre du Club
    Femme Profil pro
    Inscrit en
    Mars 2011
    Messages
    72
    Détails du profil
    Informations personnelles :
    Sexe : Femme

    Informations professionnelles :
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mars 2011
    Messages : 72
    Points : 50
    Points
    50
    Par défaut Convertir un fichier JSON dans un format XML en PHP avec DOM
    Bonsoir,
    Je veux convertir un fichier JSON (issues de Twitter contient une centaines de lignes) dansle format XML en PHP avec DOM, j'ai trouvé sur le net un code qui marche bien avec un fichier contient une dizaine des lignes, mais malheureusement avec mon fichier il m'affiche un fichier vide.
    voici mon code
    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
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
     
    <?php
     
    class Array2XML {
     
        private static $xml = null;
    	private static $encoding = 'UTF-8';
     
        /**
         * Initialize the root XML node [optional]
         * @param $version
         * @param $encoding
         * @param $format_output
         */
        public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
            self::$xml = new DomDocument($version, $encoding);
            self::$xml->formatOutput = $format_output;
    		self::$encoding = $encoding;
        }
     
        /**
         * Convert an Array to XML
         * @param string $node_name - name of the root node to be converted
         * @param array $arr - aray to be converterd
         * @return DomDocument
         */
        public static function &createXML($node_name, $arr=array()) {
            $xml = self::getXMLRoot();
            $xml->appendChild(self::convert($node_name, $arr));
     
            self::$xml = null;    // clear the xml node in the class for 2nd time use.
            return $xml;
        }
     
        /**
         * Convert an Array to XML
         * @param string $node_name - name of the root node to be converted
         * @param array $arr - aray to be converterd
         * @return DOMNode
         */
        private static function &convert($node_name, $arr=array()) {
     
            //print_arr($node_name);
            $xml = self::getXMLRoot();
            $node = $xml->createElement($node_name);
     
            if(is_array($arr)){
                // get the attributes first.;
                if(isset($arr['@attributes'])) {
                    foreach($arr['@attributes'] as $key => $value) {
                        if(!self::isValidTagName($key)) {
                            throw new Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);
                        }
                        $node->setAttribute($key, self::bool2str($value));
                    }
                    unset($arr['@attributes']); //remove the key from the array once done.
                }
     
                // check if it has a value stored in @value, if yes store the value and return
                // else check if its directly stored as string
                if(isset($arr['@value'])) {
                    $node->appendChild($xml->createTextNode(self::bool2str($arr['@value'])));
                    unset($arr['@value']);    //remove the key from the array once done.
                    //return from recursion, as a note with value cannot have child nodes.
                    return $node;
                } else if(isset($arr['@cdata'])) {
                    $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata'])));
                    unset($arr['@cdata']);    //remove the key from the array once done.
                    //return from recursion, as a note with cdata cannot have child nodes.
                    return $node;
                }
            }
     
            //create subnodes using recursion
            if(is_array($arr)){
                // recurse to get the node for that key
                foreach($arr as $key=>$value){
                    if(!self::isValidTagName($key)) {
                        throw new Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);
                    }
                    if(is_array($value) && is_numeric(key($value))) {
                        // MORE THAN ONE NODE OF ITS KIND;
                        // if the new array is numeric index, means it is array of nodes of the same kind
                        // it should follow the parent key name
                        foreach($value as $k=>$v){
                            $node->appendChild(self::convert($key, $v));
                        }
                    } else {
                        // ONLY ONE NODE OF ITS KIND
                        $node->appendChild(self::convert($key, $value));
                    }
                    unset($arr[$key]); //remove the key from the array once done.
                }
            }
     
            // after we are done with all the keys in the array (if it is one)
            // we check if it has any text value, if yes, append it.
            if(!is_array($arr)) {
                $node->appendChild($xml->createTextNode(self::bool2str($arr)));
            }
     
            return $node;
        }
     
        /*
         * Get the root XML node, if there isn't one, create it.
         */
        private static function getXMLRoot(){
            if(empty(self::$xml)) {
                self::init();
            }
            return self::$xml;
        }
     
        /*
         * Get string representation of boolean value
         */
        private static function bool2str($v){
            //convert boolean to text value.
            $v = $v === true ? 'true' : $v;
            $v = $v === false ? 'false' : $v;
            return $v;
        }
     
        /*
         * Check if the tag name or attribute name contains illegal characters
         * Ref: http://www.w3.org/TR/xml/#sec-common-syn
         */
        private static function isValidTagName($tag){
            $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
            return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
        }
    }
    $file = file_get_contents("C:/Users/DELL/Desktop/fb.json");
    json_decode($file);
    $array=json_decode($file ,true);
    $xml = Array2XML::createXML('data', $array);
     echo $xml->saveXML(). "\n";
    $xml->save('C:/Users/DELL/Desktop/fichxml.xml');
    merci d’avance pour votre aide

  2. #2
    Modérateur
    Avatar de sabotage
    Homme Profil pro
    Inscrit en
    Juillet 2005
    Messages
    29 208
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Juillet 2005
    Messages : 29 208
    Points : 44 155
    Points
    44 155
    Par défaut
    Si tu n'as rien débugué toi même, il faut nous donner le Json.
    N'oubliez pas de consulter les FAQ PHP et les cours et tutoriels PHP

  3. #3
    Membre du Club
    Femme Profil pro
    Inscrit en
    Mars 2011
    Messages
    72
    Détails du profil
    Informations personnelles :
    Sexe : Femme

    Informations professionnelles :
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mars 2011
    Messages : 72
    Points : 50
    Points
    50
    Par défaut
    Citation Envoyé par sabotage Voir le message
    Si tu n'as rien débugué toi même, il faut nous donner le Json.
    ci-joint mon fichier JSON

  4. #4
    Modérateur
    Avatar de sabotage
    Homme Profil pro
    Inscrit en
    Juillet 2005
    Messages
    29 208
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Juillet 2005
    Messages : 29 208
    Points : 44 155
    Points
    44 155
    Par défaut
    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
      "45": [
                            {
                                "id": "110689713095",
                                "name": "Val d'Isère",
                                "type": "page",
                                "offset": 45,
                                "length": 11
                            }
                        ],
                        "195": [
                            {
                                "id": "549055018503390",
                                "name": "Val d'Isère Ice Driving",
                                "type": "page",
                                "offset": 195,
                                "length": 23
                            }
                        ]
    Tu ne peux pas avoir un node XML qui commence par un chiffre donc les clef 45 et 195 ne sont pas correctes.
    N'oubliez pas de consulter les FAQ PHP et les cours et tutoriels PHP

  5. #5
    Membre du Club
    Femme Profil pro
    Inscrit en
    Mars 2011
    Messages
    72
    Détails du profil
    Informations personnelles :
    Sexe : Femme

    Informations professionnelles :
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mars 2011
    Messages : 72
    Points : 50
    Points
    50
    Par défaut
    Citation Envoyé par sabotage Voir le message
    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
      "45": [
                            {
                                "id": "110689713095",
                                "name": "Val d'Isère",
                                "type": "page",
                                "offset": 45,
                                "length": 11
                            }
                        ],
                        "195": [
                            {
                                "id": "549055018503390",
                                "name": "Val d'Isère Ice Driving",
                                "type": "page",
                                "offset": 195,
                                "length": 23
                            }
                        ]
    Tu ne peux pas avoir un node XML qui commence par un chiffre donc les clef 45 et 195 ne sont pas correctes.
    Merci pour votre réponse, mais même si je supprime ces deux clef toujours le même problème.

  6. #6
    Modérateur
    Avatar de sabotage
    Homme Profil pro
    Inscrit en
    Juillet 2005
    Messages
    29 208
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Juillet 2005
    Messages : 29 208
    Points : 44 155
    Points
    44 155
    Par défaut
    Tu as du raté ton découpage.
    Renomme les plutôt que de les supprimer.

    Et active les erreurs PHP.
    N'oubliez pas de consulter les FAQ PHP et les cours et tutoriels PHP

  7. #7
    Membre du Club
    Femme Profil pro
    Inscrit en
    Mars 2011
    Messages
    72
    Détails du profil
    Informations personnelles :
    Sexe : Femme

    Informations professionnelles :
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Mars 2011
    Messages : 72
    Points : 50
    Points
    50
    Par défaut
    Citation Envoyé par sabotage Voir le message
    Tu as du raté ton découpage.
    Renomme les plutôt que de les supprimer.

    Et active les erreurs PHP.
    Merci bcp ça marche merci pour votre aide
    En faite,j'ai renommé tous les nœuds qui commence par un chiffre

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

Discussions similaires

  1. Convertir un fichier JSON dans un format XML en PHP
    Par imen.m dans le forum Langage
    Réponses: 6
    Dernier message: 11/09/2015, 16h46
  2. Arborescence de fichiers representee dans un document xml
    Par saragaglia dans le forum XML/XSL et SOAP
    Réponses: 1
    Dernier message: 25/01/2009, 18h38
  3. Convertir un fichier xls dans une base mysql
    Par matinho dans le forum Débuter
    Réponses: 2
    Dernier message: 10/11/2008, 14h15
  4. Convertir un fichier .jar dans un autre format.
    Par Strappal dans le forum Java ME
    Réponses: 2
    Dernier message: 29/06/2006, 19h32
  5. fichier de sauvegarde au format XML
    Par freecell31 dans le forum XML/XSL et SOAP
    Réponses: 2
    Dernier message: 22/05/2006, 00h26

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