[SPIP] ~v3.0.20-->v3.0.25
[lhc/web/clavette_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-2016 *
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')) return;
14
15
16
17
18 /**
19 * Transforme un texte XML en tableau PHP
20 * @param string|object $u
21 * @param bool $utiliser_namespace
22 * @return array
23 */
24 function inc_simplexml_to_array_dist($u, $utiliser_namespace=false){
25 // decoder la chaine en SimpleXML si pas deja fait
26 if (is_string($u))
27 $u = simplexml_load_string($u);
28 return array('root'=>@xmlObjToArr($u, $utiliser_namespace));
29 }
30
31
32 /**
33 * Transforme un objet SimpleXML en tableau PHP
34 * http://www.php.net/manual/pt_BR/book.simplexml.php#108688
35 * xaviered at gmail dot com 17-May-2012 07:00
36 *
37 * @param object $obj
38 * @param bool $utiliser_namespace
39 * @return array
40 **/
41 function xmlObjToArr($obj, $utiliser_namespace=false) {
42
43 $tableau = array();
44
45 // Cette fonction getDocNamespaces() est longue sur de gros xml. On permet donc
46 // de l'activer ou pas suivant le contenu supposé du XML
47 if (is_object($obj)) {
48 if (is_array($utiliser_namespace)){
49 $namespace = $utiliser_namespace;
50 }
51 else {
52 if ($utiliser_namespace)
53 $namespace = $obj->getDocNamespaces(true);
54 $namespace[NULL] = NULL;
55 }
56
57 $name = strtolower((string)$obj->getName());
58 $text = trim((string)$obj);
59 if (strlen($text) <= 0) {
60 $text = NULL;
61 }
62
63 $children = array();
64 $attributes = array();
65
66 // get info for all namespaces
67 foreach( $namespace as $ns=>$nsUrl ) {
68 // attributes
69 $objAttributes = $obj->attributes($ns, true);
70 foreach( $objAttributes as $attributeName => $attributeValue ) {
71 $attribName = strtolower(trim((string)$attributeName));
72 $attribVal = trim((string)$attributeValue);
73 if (!empty($ns)) {
74 $attribName = $ns . ':' . $attribName;
75 }
76 $attributes[$attribName] = $attribVal;
77 }
78
79 // children
80 $objChildren = $obj->children($ns, true);
81 foreach( $objChildren as $childName=>$child ) {
82 $childName = strtolower((string)$childName);
83 if( !empty($ns) ) {
84 $childName = $ns.':'.$childName;
85 }
86 $children[$childName][] = xmlObjToArr($child, $namespace);
87 }
88 }
89
90 $tableau = array(
91 'name'=>$name,
92 );
93 if ($text)
94 $tableau['text'] = $text;
95 if ($attributes)
96 $tableau['attributes'] = $attributes;
97 if ($children)
98 $tableau['children'] = $children;
99 }
100
101 return $tableau;
102 }
103
104 ?>