0ed567b4afce7d35b07c0faf359aaf516810bf05
[lhc/web/www.git] / www / ecrire / inc / simplexml_to_array.php
1 <?php
2
3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
5 * *
6 * Copyright (c) 2001-2017 *
7 * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
8 * *
9 * Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
10 * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
11 \***************************************************************************/
12
13 if (!defined('_ECRIRE_INC_VERSION')) {
14 return;
15 }
16
17
18 /**
19 * Transforme un texte XML en tableau PHP
20 *
21 * @param string|object $u
22 * @param bool $utiliser_namespace
23 * @return array
24 */
25 function inc_simplexml_to_array_dist($u, $utiliser_namespace = false) {
26 // decoder la chaine en SimpleXML si pas deja fait
27 if (is_string($u)) {
28 $u = simplexml_load_string($u);
29 }
30
31 return array('root' => @xmlObjToArr($u, $utiliser_namespace));
32 }
33
34
35 /**
36 * Transforme un objet SimpleXML en tableau PHP
37 * http://www.php.net/manual/pt_BR/book.simplexml.php#108688
38 * xaviered at gmail dot com 17-May-2012 07:00
39 *
40 * @param object $obj
41 * @param bool $utiliser_namespace
42 * @return array
43 **/
44 function xmlObjToArr($obj, $utiliser_namespace = false) {
45
46 $tableau = array();
47
48 // Cette fonction getDocNamespaces() est longue sur de gros xml. On permet donc
49 // de l'activer ou pas suivant le contenu supposé du XML
50 if (is_object($obj)) {
51 if (is_array($utiliser_namespace)) {
52 $namespace = $utiliser_namespace;
53 } else {
54 if ($utiliser_namespace) {
55 $namespace = $obj->getDocNamespaces(true);
56 }
57 $namespace[null] = null;
58 }
59
60 $name = strtolower((string)$obj->getName());
61 $text = trim((string)$obj);
62 if (strlen($text) <= 0) {
63 $text = null;
64 }
65
66 $children = array();
67 $attributes = array();
68
69 // get info for all namespaces
70 foreach ($namespace as $ns => $nsUrl) {
71 // attributes
72 $objAttributes = $obj->attributes($ns, true);
73 foreach ($objAttributes as $attributeName => $attributeValue) {
74 $attribName = strtolower(trim((string)$attributeName));
75 $attribVal = trim((string)$attributeValue);
76 if (!empty($ns)) {
77 $attribName = $ns . ':' . $attribName;
78 }
79 $attributes[$attribName] = $attribVal;
80 }
81
82 // children
83 $objChildren = $obj->children($ns, true);
84 foreach ($objChildren as $childName => $child) {
85 $childName = strtolower((string)$childName);
86 if (!empty($ns)) {
87 $childName = $ns . ':' . $childName;
88 }
89 $children[$childName][] = xmlObjToArr($child, $namespace);
90 }
91 }
92
93 $tableau = array(
94 'name' => $name,
95 );
96 if ($text) {
97 $tableau['text'] = $text;
98 }
99 if ($attributes) {
100 $tableau['attributes'] = $attributes;
101 }
102 if ($children) {
103 $tableau['children'] = $children;
104 }
105 }
106
107 return $tableau;
108 }