2 /*************************************************************************/
3 /* This class stores associative arrays in an xml formatted string. */
4 /* There's also a function thar retrieves them. If you try to use */
5 /* xml2array with a general xml, it can fail, since there can be some */
6 /* repeated indexes.... */
7 /* Source: http://www.phpclasses.org/browse/package/2286/ */
8 /*************************************************************************/
10 class yourls_array2xml {
12 var $arrays, $keys, $node_flag, $depth, $xml_parser;
13 /*Converts an array to an xml string*/
14 function array2xml($array) {
16 $this->text="<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><result>";
17 $this->text.= $this->array_transform($array);
18 $this->text .="</result>";
22 function array_transform($array){
24 foreach($array as $key => $value){
25 if(!is_array($value)){
26 //BEGIN code mod by Doug Vanderweide, 13 Jan 2011
27 //does $value contain html entities?
28 if(strlen($value) != strlen(htmlentities($value))) {
29 //if so, encode as CDATA
30 $value = "<![CDATA[" . htmlentities($value) . "]]>";
32 $this->text .= "<$key>$value</$key>";
35 $this->text.="<$key>";
36 $this->array_transform($value);
37 $this->text.="</$key>";
43 /*Transform an XML string to associative array "XML Parser Functions"*/
44 function xml2array($xml){
46 $this->xml_parser = xml_parser_create();
47 xml_set_object($this->xml_parser, $this);
48 xml_parser_set_option ($this->xml_parser,XML_OPTION_CASE_FOLDING,0);//Don't put tags uppercase
49 xml_set_element_handler($this->xml_parser, "startElement", "endElement");
50 xml_set_character_data_handler($this->xml_parser,"characterData");
51 xml_parse($this->xml_parser,$xml,true);
52 xml_parser_free($this->xml_parser);
53 return $this->arrays[0];
56 function startElement($parser, $name, $attrs)
58 $this->keys[]=$name; //We add a key
62 function characterData($parser,$data)
64 $key=end($this->keys);
65 $this->arrays[$this->depth][$key]=$data;
66 $this->node_flag=0; //So that we don't add as an array, but as an element
68 function endElement($parser, $name)
70 $key=array_pop($this->keys);
71 //If $node_flag==1 we add as an array, if not, as an element
72 if($this->node_flag==1){
73 $this->arrays[$this->depth][$key]=$this->arrays[$this->depth+1];
74 unset($this->arrays[$this->depth+1]);