Classe pour générer des fichiers XML

Une classe pour générer des fichiers XML, des explications sont dans le code. Elle est compatible PHP 7.4 et PHP 8.3, avec typage, avec la syntaxe magique __call.

Et un exemple d'utilisation pour générer un fichier XML.



Information sur les mises à jour

Dernière mise à jour :

22 Oct 2019
fonctionnement du code vérifié

03 Mars 2026
fonctionnement du code vérifié
refactoring du code en PHP 8

7 556  vues
Compatibilité du code
PHP 8
  code classé dans   XML
  code source classé dans   XML
 
01
02
03
04
05
06
07
08
09
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
                    
<?php
/*------------------------------*/
/*
Titre : Classe pour générer des fichiers XML

Auteur : erwan
Date édition : 07 Fev 2010
Date mise a jour : 22 Oct 2019

Rapport de la maj:
- fonctionnement du code vérifié
Date mise a jour : 03 Mars 2026

Rapport de la maj:
- fonctionnement du code vérifié
- refactoring du code en PHP 8
*/
/*------------------------------*/

class XML
{
private string $head = '';
private string $key;
private string $value;
/** @var array<string, string> */
private array $attributs;
/** @var XML[] */
private array $tree = [];

public function __construct(string $key, string $value = '', array
$attributs = [])
{
$this->key = strtolower($key);
$this->value = $value;
$this->attributs = $attributs;
}

public function setHead(string $head): void
{
$this->head = $head;
}

public function addNode(XML $node): void
{
$this->tree[] = $node;
}

public function addAttribut(string $key, string $value): void
{
$this->attributs[$key] = $value;
}

public function __toString(): string
{
$text = $this->head !== '' ? $this->head . "\n" : '';

$text .= '<' . $this->key;

foreach ($this->attributs as $attrKey => $attrValue) {
// Sécurité minimale contre les injections dans les attributs
$attrValue = htmlspecialchars($attrValue, ENT_QUOTES | ENT_XML1,
'UTF-8');
$text .= ' ' . $attrKey . '="' . $attrValue . '"';
}

$text .= '>';

// Contenu texte uniquement s'il existe
if ($this->value !== '') {
$text .= "\n" . htmlspecialchars($this->value, ENT_QUOTES | ENT_XML1
, 'UTF-8') . "\n";
}

// Enfants
foreach ($this->tree as $node) {
$text .= (string)$node;
}

$text .= '</' . $this->key . '>' . "\n";

// Nettoyage des doubles (ou plus) sauts de ligne
$text = preg_replace('/\n{2,}/', "\n", $text);

return $text;
}

/**
* Méthode magique pour ajouter des nœuds facilement :
* $contact->addNom('Dupond');
* $contact->addAdresse('12 rue...', ['type' => 'principale']);
*/
public function __call(string $name, array $arguments)
{
if (str_starts_with($name, 'add')) {
$key = substr($name, 3); // nom ? Nom ? nom
$key = strtolower($key);

$value = $arguments[0] ?? '';
$attributs = $arguments[1] ?? [];

if (!is_string($value)) {
$value = (string)$value;
}

$child = new self($key, $value, $attributs);
$this->addNode($child);

return $child;
// ? bonus : on retourne l'enfant créé (chaînage possible)
}

trigger_error("Méthode $name inexistante", E_USER_WARNING);
return null;
}
}
?>
<?php
/*------------------------------*/
/*
Titre : Classe pour générer des fichiers XML

Auteur : erwan
Date édition : 07 Fev 2010
Date mise a jour : 22 Oct 2019

Rapport de la maj:
- fonctionnement du code vérifié
Date mise a jour : 03 Mars 2026

Rapport de la maj:
- fonctionnement du code vérifié
- refactoring du code en PHP 8
*/
/*------------------------------*/

class XML
{
private string $head = '';
private string $key;
private string $value;
/** @var array<string, string> */
private array $attributs;
/** @var XML[] */
private array $tree = [];

public function __construct(string $key, string $value = '', array
$attributs = [])
{
$this->key = strtolower($key);
$this->value = $value;
$this->attributs = $attributs;
}

public function setHead(string $head): void
{
$this->head = $head;
}

public function addNode(XML $node): void
{
$this->tree[] = $node;
}

public function addAttribut(string $key, string $value): void
{
$this->attributs[$key] = $value;
}

public function __toString(): string
{
$text = $this->head !== '' ? $this->head . "\n" : '';

$text .= '<' . $this->key;

foreach ($this->attributs as $attrKey => $attrValue) {
// Sécurité minimale contre les injections dans les attributs
$attrValue = htmlspecialchars($attrValue, ENT_QUOTES | ENT_XML1,
'UTF-8');
$text .= ' ' . $attrKey . '="' . $attrValue . '"';
}

$text .= '>';

// Contenu texte uniquement s'il existe
if ($this->value !== '') {
$text .= "\n" . htmlspecialchars($this->value, ENT_QUOTES | ENT_XML1
, 'UTF-8') . "\n";
}

// Enfants
foreach ($this->tree as $node) {
$text .= (string)$node;
}

$text .= '</' . $this->key . '>' . "\n";

// Nettoyage des doubles (ou plus) sauts de ligne
$text = preg_replace('/\n{2,}/', "\n", $text);

return $text;
}

/**
* Méthode magique pour ajouter des nœuds facilement :
* $contact->addNom('Dupond');
* $contact->addAdresse('12 rue...', ['type' => 'principale']);
*/
public function __call(string $name, array $arguments)
{
if (str_starts_with($name, 'add')) {
$key = substr($name, 3); // nom ? Nom ? nom
$key = strtolower($key);

$value = $arguments[0] ?? '';
$attributs = $arguments[1] ?? [];

if (!is_string($value)) {
$value = (string)$value;
}

$child = new self($key, $value, $attributs);
$this->addNode($child);

return $child;
// ? bonus : on retourne l'enfant créé (chaînage possible)
}

trigger_error("Méthode $name inexistante", E_USER_WARNING);
return null;
}
}
?>

Exemple :

 
01
02
03
04
05
06
07
08
09
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
                    
<?php

$carnet = new XML('carnet');
$carnet->setHead('<?xml version="1.0" encoding="UTF-8"?>');

$contact = new XML('contact');
$contact->addNom('Dupond');
$contact->addPrenom('Jean');
$contact->addTel('0123456789', ['type' => 'mobile']);
$contact->addEmail('jean.dupond@example.com');

$carnet->addNode($contact);

// Deuxième contact pour voir
$contact2 = new XML('contact');
$contact2->addNom('Martin');
$contact2->addPrenom('Sophie');
$contact2->addTel('0687654321');

$carnet->addNode($contact2);

echo $carnet;

// Affiche :

<?xml version="1.0" encoding="UTF-8"?>
<carnet><contact><nom>
Dupond
</nom>
<prenom>
Jean
</prenom>
<tel type="mobile">
0123456789
</tel>
<email>
jean.dupond@example.com
</email>
</contact>
<contact><nom>
Martin
</nom>
<prenom>
Sophie
</prenom>
<tel>
0687654321
</tel>
</contact>
</carnet>
<?php

$carnet = new XML('carnet');
$carnet->setHead('<?xml version="1.0" encoding="UTF-8"?>');

$contact = new XML('contact');
$contact->addNom('Dupond');
$contact->addPrenom('Jean');
$contact->addTel('0123456789', ['type' => 'mobile']);
$contact->addEmail('jean.dupond@example.com');

$carnet->addNode($contact);

// Deuxième contact pour voir
$contact2 = new XML('contact');
$contact2->addNom('Martin');
$contact2->addPrenom('Sophie');
$contact2->addTel('0687654321');

$carnet->addNode($contact2);

echo $carnet;

// Affiche :

<?xml version="1.0" encoding="UTF-8"?>
<carnet><contact><nom>
Dupond
</nom>
<prenom>
Jean
</prenom>
<tel type="mobile">
0123456789
</tel>
<email>
jean.dupond@example.com
</email>
</contact>
<contact><nom>
Martin
</nom>
<prenom>
Sophie
</prenom>
<tel>
0687654321
</tel>
</contact>
</carnet>

      Fonctions du code - Doc officielle PHP

   php.net  
Description
Versions PHP
    array
Crée un tableau
PHP 4, 5, 7 et 8
    echo
Affiche une chaîne de caractères
PHP 4, 5, 7 et 8
    htmlspecialchars
Convertit les caractères spéciaux en entités HTML
PHP 4, 5, 7 et 8
    is_string
Détermine si une variable est de type chaîne de caractères
PHP 4, 5, 7 et 8
    preg_replace
Rechercher et remplacer par expression rationnelle standard
PHP 4, 5, 7 et 8
    return
Retourne le controle du programme au module appelant
PHP 4, 5, 7 et 8
    strtolower
Renvoie une chaîne en minuscules
PHP 4, 5, 7 et 8
    str_starts_with
Détermine si une chaîne commence par une sous-chaîne donnée
PHP 8
    substr
Retourne un segment de chaîne
PHP 4, 5, 7 et 8
    trigger_error
Déclenche une erreur utilisateur
PHP 4, 5, 7 et 8
Minimum 10 mots. Votre commentaire sera visible après validation.


 Autres snippets qui pourraient vous intéresser

Réécrit un nom valide à vos fichiers pour l'upload

Compatibilité : PHP 5, PHP 7, PHP 8

Lorsque vous transférez un fichier par upload, le nom du fichier se trouvant sur votre site doit être valide. Il est conseillé d'utiliser cette fonction.

Classe Gtitrentitrerique - PHP Sources

Compatibilité : PHP 7

Classe abstraite offrant de nombreuses fonctionnalités : sauvegarde/chargement dans une base de données, sauvegarde/chargement dans une variable

* Requêtes exécutées avec Recherche Contextuelle

  Les derniers scripts

PHP 8.5.5

logo PHP
Langue langue us
Date 12 Avril
Taille 32 Mo
Catégorie PHP

PHP 8.4.20

logo PHP
Langue langue us
Date 12 Avril
Taille 30 Mo
Catégorie PHP

Serendipity 2.6.0

logo Serendipity
Langue langue fr
Date 11 Avril
Taille 15 Mo
Catégorie Blogs

Drupal 11.3.6

logo Drupal
Langue langue us
Date 11 Avril
Taille 34 Mo
Catégorie CMS

TYPO3 14.2.0

logo TYPO3
Langue langue fr
Date 10 Avril
Taille 38 Mo
Catégorie CMS

Dolibarr ERP 23.0.1

logo Dolibarr ERP
Langue langue fr
Date 09 Avril
Taille 89 Mo
Catégorie Logiciels