xml2array() - XML Parser for PHP

xml2arry() Logo

xml2array() is a easy to use PHP function that will convert the given XML text to an array in the XML structure. Kind of like my Javascript xml2array() function.

Demo

See a Sample - the output of this function.

See a demo.

Code

<?php
/**
 * xml2array() will convert the given XML text to an array in the XML structure.
 * Link: http://www.bin-co.com/php/scripts/xml2array/
 * Arguments : $contents - The XML text
 *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
 *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
 * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
 * Examples: $array =  xml2array(file_get_contents('feed.xml'));
 *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute'));
 */
function xml2array($contents$get_attributes=1$priority 'tag') {
    if(!
$contents) return array();

    if(!
function_exists('xml_parser_create')) {
        
//print "'xml_parser_create()' function not found!";
        
return array();
    }

    
//Get the XML parser of PHP - PHP must have this module for the parser to work
    
$parser xml_parser_create('');
    
xml_parser_set_option($parserXML_OPTION_TARGET_ENCODING"UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
    
xml_parser_set_option($parserXML_OPTION_CASE_FOLDING0);
    
xml_parser_set_option($parserXML_OPTION_SKIP_WHITE1);
    
xml_parse_into_struct($parsertrim($contents), $xml_values);
    
xml_parser_free($parser);

    if(!
$xml_values) return;//Hmm...

    //Initializations
    
$xml_array = array();
    
$parents = array();
    
$opened_tags = array();
    
$arr = array();

    
$current = &$xml_array//Refference

    //Go through the tags.
    
$repeated_tag_index = array();//Multiple tags with same name will be turned into an array
    
foreach($xml_values as $data) {
        unset(
$attributes,$value);//Remove existing values, or there will be trouble

        //This command will extract these variables into the foreach scope
        // tag(string), type(string), level(int), attributes(array).
        
extract($data);//We could use the array by itself, but this cooler.

        
$result = array();
        
$attributes_data = array();
        
        if(isset(
$value)) {
            if(
$priority == 'tag'$result $value;
            else 
$result['value'] = $value//Put the value in a assoc array if we are in the 'Attribute' mode
        
}

        
//Set the attributes too.
        
if(isset($attributes) and $get_attributes) {
            foreach(
$attributes as $attr => $val) {
                if(
$priority == 'tag'$attributes_data[$attr] = $val;
                else 
$result['attr'][$attr] = $val//Set all the attributes in a array called 'attr'
            
}
        }

        
//See tag status and do the needed.
        
if($type == "open") {//The starting of the tag '<tag>'
            
$parent[$level-1] = &$current;
            if(!
is_array($current) or (!in_array($tagarray_keys($current)))) { //Insert New tag
                
$current[$tag] = $result;
                if(
$attributes_data$current[$tag'_attr'] = $attributes_data;
                
$repeated_tag_index[$tag.'_'.$level] = 1;

                
$current = &$current[$tag];

            } else { 
//There was another element with the same tag name

                
if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
                    
$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    
$repeated_tag_index[$tag.'_'.$level]++;
                } else {
//This section will make the value an array if multiple tags with the same name appear together
                    
$current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
                    
$repeated_tag_index[$tag.'_'.$level] = 2;
                    
                    if(isset(
$current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                        
$current[$tag]['0_attr'] = $current[$tag.'_attr'];
                        unset(
$current[$tag.'_attr']);
                    }

                }
                
$last_item_index $repeated_tag_index[$tag.'_'.$level]-1;
                
$current = &$current[$tag][$last_item_index];
            }

        } elseif(
$type == "complete") { //Tags that ends in 1 line '<tag />'
            //See if the key is already taken.
            
if(!isset($current[$tag])) { //New Key
                
$current[$tag] = $result;
                
$repeated_tag_index[$tag.'_'.$level] = 1;
                if(
$priority == 'tag' and $attributes_data$current[$tag'_attr'] = $attributes_data;

            } else { 
//If taken, put all things inside a list(array)
                
if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...

                    // ...push the new element into that array.
                    
$current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
                    
                    if(
$priority == 'tag' and $get_attributes and $attributes_data) {
                        
$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                    }
                    
$repeated_tag_index[$tag.'_'.$level]++;

                } else { 
//If it is not an array...
                    
$current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
                    
$repeated_tag_index[$tag.'_'.$level] = 1;
                    if(
$priority == 'tag' and $get_attributes) {
                        if(isset(
$current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
                            
                            
$current[$tag]['0_attr'] = $current[$tag.'_attr'];
                            unset(
$current[$tag.'_attr']);
                        }
                        
                        if(
$attributes_data) {
                            
$current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
                        }
                    }
                    
$repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
                
}
            }

        } elseif(
$type == 'close') { //End of tag '</tag>'
            
$current = &$parent[$level-1];
        }
    }
    
    return(
$xml_array);

Comments

eviL3 at 20 Jan, 2007 04:51
This seems to be the best xml parsing function that exists...

I'm very impressed.

I was wondering what's the license of the function? I'd like to use it for GPL projects, is that okay?

Thanks!
Reply to this.
Binny V A at 10 Feb, 2007 10:27
Sorry I did not specify the license - its in BSD License. Feel free to use it
anywhere.
Reply to this.
Anonymous at 09 Feb, 2007 05:02
Ok We now have the data in arrays but how do I call the data back from the arrays say

$contents = file_get_contents('sample.xml');//Or however you what it
$result = xml2array($contents);
so if one of my arrays is called say LAT and has a value of 100 how do I reference
it in my php? say echo $LAT[0];
//print_r($result);
Reply to this.
Binny V A at 10 Feb, 2007 10:31
If you do a print_r() with the resulting array(in the example it is $result), you will see the structure of the Array - you will understand how to refer it.
Reply to this.
Justin at 09 Dec, 2007 07:49
Can you please give an example of how to reference the information in the array?
Reply to this.
Pete at 04 Mar, 2007 06:56
I am a beginner at php, would it be possible to give me an example of how to read the array values into variables to upload to a mysql database?
Thanks
Reply to this.
Binny V A at 05 Mar, 2007 04:30
Its easy - I cannot give the answer here as I need to know the fields in your table to write the query.
Reply to this.
marije at 10 Mar, 2007 10:46
I have a xml node, containing html tags such as

and <li> and and they are not giving back the way I would want it. Is there a solution for this ??

example node:
<Tekst>

xxxxx.</li>
<li>yyyyy.</li>
<li>vvvvv.</li>
<li>qqqqq.</li>
News



zzzzz.




</Tekst>

$contents,0 gives : Array ( [p] => xxxxx. )
$contents gives : Array ( [p] => Array ( [value] => xxxxx. [attr] => Array ( [align] => justify ) ) )

Reply to this.
Neil at 30 May, 2007 06:19
Just looking at the code, a little confused. Where is this $level variable set?
Reply to this.
Binny V A at 31 May, 2007 06:54
Good question! The $level variable is one of the variables that is created by the statement 'extract($data);'. The other variables created are tag(string), type(string), level(int), attributes(array).

Sorry about the confusion. If you have any more doubts(I am sure you will - the code is complicated, don't hesitate to email me. My email is binnyva, gmail.
Reply to this.
Anonymous at 30 Jul, 2007 01:44
nice function, however it doesn't help when the number of elements is random. i.e.

the following xml, the message array contains 2 elements
<messageList>
<message>
<from>2</from>
<to>1</to>
<text>adf</text>
</message>
<message>
<from>3</from>
<to>4</to>
<text>bla adf</text>
</message>
</messageList>


in this case the message array contains 4 elements.
<messageList>
<message>
<from>2</from>
<to>1</to>
<text>adf</text>
</message>
</messageList>

There's isn't an easy way to determine how many messages are being passed.
Reply to this.
Binny V A at 01 Aug, 2007 06:07
True - you have to know the schema of the XML beforehand. This is a big defect of this library. Unfortunately, this cannot be solved without compromising the simplicity of the function.
Reply to this.
hsaturn at 09 Jul, 2009 06:34
hsaturn at 09 Jul, 2009 06:33
See my solution to that problem
by searching hsaturn at 07 Jul, 2009 08:29
Reply to this.
LT at 08 May, 2008 07:18
If you don't like actual way:


} elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
//See if the key is already taken.
if(!isset($current[$tag])) { //New Key
$current[$tag] = array($result);

// last line just creates first element already in the array.
// enjoy!
Reply to this.
hsaturn at 09 Jul, 2009 06:33
See my solution to that problem
by searching hsaturn at 07 Jul, 2009 08:29
Reply to this.
Me at 19 Sep, 2007 01:51
Man, this is really the simpliest xml parser that i found, and the best, if you know the xml schema, for my app it will be used for a webservice, so i'll know the schema before.
Reply to this.
sopppas at 30 Sep, 2007 09:55
add utf8_decode at line 33 for utf8 support:

if(isset($value)) $result['value'] = utf8_decode($value);

great piece of coding!
Reply to this.
Mike at 16 Oct, 2007 07:49
Thanks, this parser works really well.

I just have a quick question, how would i go about putting the resulting data into a mysql database?

I am a real newbie and cant for the life of me see/understand how to do it.
Reply to this.
jonal at 24 Oct, 2007 02:41
First of all! Your parser actually made my day! Excellent work! :-)
Reply to this.
Wim at 30 Oct, 2007 12:41
Great parser!

However, I am looking for a result which is somewhere in between of the 2 modes results this function is producing. I would like the attribute value of a tag to be included like the other tags inside the attributed tag in the result array, but without everything being array values. Is there a simple way of doing this?

like this: xml: <home id="1045">100000....y</home>

In the result array it should look like: home[id], home[price], home[available] etc.



Reply to this.
DaHopi at 31 Oct, 2007 06:08
Great! I'm impressed.
Best function i found in the net..
Greetz from Germany and thanks a lot!
Reply to this.
GrwN at 12 Nov, 2007 02:58
Idd, Great Parser!
I'm planning to use this for an API module i'm writing.
If it's ok by you, i'm gonna publish it with this parser.
Greets, GrwN
Reply to this.
Deepak at 05 Dec, 2007 12:28
This is the wonderful code.no doubt abt it?
but just i wants to know that how to extract the array results and store that value in a variable like $xyz.so on...
Just i wants to enter that variable in my database after retriving these values from the xml file.
Reply to this.
Pk at 07 Jan, 2008 03:43
Hi,
this parser works really well,
but i have a problem under php 5.2.4 that return
"Fatal error: Cannot use string
offset as an array in"

This is my code:

$parsedBis = xml2array($xmlfileBis,0);
print_r($parsedBis);

output:
Array
(
[products] => Array
(
[categories] =>
)

)


Fatal error: Cannot use string offset as an array in /prod/doc/site/products/index.php on line 18



PS
under php 5.1.6 and php 4 it works correctly

Reply to this.
Binny V A at 16 Jan, 2008 11:19
Hmm - never ran across that error. I think its a bug in that specific PHP version - although I am not sure.
Reply to this.
Robbie at 03 Dec, 2009 09:52
This behaviour happens when one or more of the XML file's fields contains a
.
Reply to this.
Robbie at 03 Dec, 2009 09:52
... thread interpreted the character... that was meant to say when it contains a < br / > (save spaces)
Reply to this.
David at 21 Jan, 2008 05:16
Is there a reverse function, array2xml?
Reply to this.
Vladimir Sokolov at 21 Nov, 2008 01:48
Here it is. Use mine code foe example.

REMARKS:
1. Rename xml2array function into basexml2array
2. Do not use 'item' as index name in accoc array



function array2xml($array, $indent = 0){
$xml = '';
foreach($array as $key => $value){
if (is_numeric($key)) {
$key = 'item';
}
$xml .= str_repeat(' ', $indent);
$xml .= "<$key>";

if(is_array($value)){
$xml .= "\n" . array2xml($value, $indent + 1);
$xml .= str_repeat(' ', $indent);
} else{
$xml .= $value;
}
$xml .= '</'.(($pos = strpos($key, ' ')) ? substr($key, 0, $pos) : $key).">\n";
}

return $xml;
}

function xml2array($contents) {
$curArray = basexml2array($contents);
return replaceItems($curArray);;
}

function replaceItems($data) {
$index = 0;
$resArray = array();
foreach ($data as $key => $value) {
if ($key == 'item') {
$key = $index++;
}
$resArray[$key] = is_array($value) ? replaceItems($value) : $value;
}
return $resArray;
}
Reply to this.
Mihai at 27 Jan, 2008 07:45
Really great function! Marvelous!

To get the results you can use:
print_r ($array['rss']['channel']['item'][$i]['title']['value']);

if you look into an RSS feed from a weblog you can find the same dropdown structure. You can then adapt it to your needs!

Cheers Binny! Thanks!
Reply to this.
Anonymous at 22 Feb, 2008 02:30
This routine doesn't store an array with one element in the same manner as multiple entry arrays.
I'm using the eBay APIs which may return one or more elements. The XML structure is the same regardless of the number of entries.

Also I suggest adding a version number to the header comments.

Single entry:
Array
(
[Item] => Array
(
[ItemID] => Array
(
[value] => 150216600790
)

Multiple entries:
Array
(
[Item] => Array
(
[0] => Array
(
[ItemID] => Array
(
[value] => 150216600790
)


Reply to this.
Jake at 19 Mar, 2008 12:11
If I include html in the xml, how do i get it to parse correctly?
Reply to this.
Anonymous at 19 Mar, 2008 02:21
Good work! Have tried out a lot of parsers for my project and they all sucked except this one! This was also the simplest. Thanks for providing it!
// Mikael from Sweden
Reply to this.
Anonymous at 10 Apr, 2008 12:13
Is there a way for the code to continue even if it finds a special chars in the XML (ie: Éé)
Reply to this.
Anonymous at 10 Apr, 2008 12:40
Is there a way fot special char. to be display (ie: Éééé) the code won't go past an accent.

thanks
Reply to this.
Binny V A at 13 Apr, 2008 10:04
I am looking into this issue - this page will be updated once I fix this bug.
Reply to this.
Anonymous at 09 Jul, 2008 08:32
I found a workaround, you just need to remove all the accent to your content file via a simple funtion.
ex.:
Function removeaccent($text)
{
$string= strtr($text,
"ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ",
"AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn");

return $string;
} ;

which gives:

$contents = file_get_contents('myXML file');
$correctcontent = removeaccent($contents);
$result = xml2array($correctcontent);

and it worked.

thanks
Reply to this.
Anonymous at 25 Apr, 2008 04:00
Hi, I can get the value inside xml tags but I can't get the tag name itself!
Example:

XML CODE

<general>
<context>default</context>
<srvlookup>yes</srvlookup>
</general>

What I want is to parse the tags and their contents so I can write it into a text file. Example:

[general]
context=default
srvlookup=yes

I get the value with: echo $array['general']['context']['value'];

Any idea on how to get the tag's name? Thank you.
Reply to this.
Anonymous at 25 Apr, 2008 04:54
After lots of research I finally managed to make it, maybe it's useful for somebody. This is what worked for me:

while (list($i) = each ($result)) {
while (list($j) = each ($result[$i])){
echo "[".$j."]
";
while (list($k) = each ($result[$i][$j])){
echo $k."=";
while(list($h) = each ($result[$i][$j][$k])){
echo $result[$i][$j][$k][$h]."
";
}
}
echo "
";
}
}
Reply to this.
Anonymous at 01 May, 2008 10:01
Below my schema,
Can anyone give me a hint, how to read the values IN trkpt....
Thanks....


“<?xml version="1.0" encoding="UTF-8" standalone="no" ?>”
<gpx
xmlns="http://www.topografix.com/GPX/1/1"
<metadata>
</metadata>
<trk>
<name>Huidig nummer: 26 APR 2008 08:12
</name>
<trkseg>
<trkpt lat="52.219812" lon="5.996262">
<ele>11.19</ele>
<time>2008-04-26T06:12:10Z</time>
<extensions>
<gpxtpx:TrackPointExtension>
<gpxtpx:atemp>27.3</gpxtpx:atemp>
</gpxtpx:TrackPointExtension>
</extensions>
</trkpt>

<trkpt lat="52.219872" lon="5.996397">
More trkpt…


</trkseg>
</trk>
</gpx>
Reply to this.
taxoft at 30 Apr, 2009 03:01
Hello, there are two ways - first you can set $priority parameter to 'attribute' - but then the output will be less readable. Second better way - copy the line setting attributes:

if (isset ($attributes) and $get_attributes)
{
foreach ($attributes as $attr => $val)
{
if ($priority == 'tag') {
$attributes_data[$attr] = $val;
// copied line:
$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'

}
else
$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
}
}

Hope this helps.
Jiri

P.S. Many thanks to authors for this function.
Reply to this.
Saul Rosenberg at 06 May, 2008 07:41
Love the parser. Works phenomenally on Firefox (development platform). I am running up against a problem in IE7 that throws an error at:

if(assoc && arr_count == 1) {
if(arr[key]) { //If another element exists with the same tag name before,
// put it in a numeric array.
//Find out how many time this parent made its appearance

The error is about arr[key] and says that "undefined is null or not an object".

Is there an update to XML2Array() that fixes this?
Reply to this.
Binny V A at 06 May, 2008 11:23
I am not sure I understand - this is a server side script - browser differences don't affect it.
Reply to this.
Saul Rosenberg at 08 May, 2008 05:26
My mistake... there is an xml2array() function defined in javascript as well. I goofed and went to the wrong site. I am going to give this script a whirl as well because I have a php side XML parsing need. Thanks!
Reply to this.
Anonymous at 06 May, 2008 11:01
I'm facing the same problem as "Anonymous at 22 Feb, 2008 02:30"
reading the array's.
Is there a fix for this problem?

Anonymous at 22 Feb, 2008 02:30
This routine doesn't store an array with one element in the same manner as multiple entry arrays.
I'm using the eBay APIs which may return one or more elements. The XML structure is the same regardless of the number of entries.
Reply to this.
LT at 08 May, 2008 06:49
Thanks for posting it!
It's really working :)
Reply to this.
LT at 08 May, 2008 07:22
If you will have randomize number of elements in the tags, change your code to this:


} elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
//See if the key is already taken.
if(!isset($current[$tag])) { //New Key
$current[$tag] = array($result);

// last line just creates first element already in the array.
// enjoy!
Reply to this.
Bauer at 13 May, 2008 01:44
Hi all,
this function have problem whit big xml:

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 93633696 bytes) in /var/www/vhosts/example.com/test.php on line 97

:(
Reply to this.
Binny V A at 14 May, 2008 11:31
How big is this XML file - in MB?
Reply to this.
Javier at 03 Jun, 2008 10:02
I like see a example for this too:

I am a beginner at php, would it be possible to give me an example of how to read the array values into variables to upload to a mysql database?

TIA,
Javier
Reply to this.
kraiosis at 19 Jun, 2008 10:00
$contents = file_get_contents('http://gd.mlb.com/components/game/mlb/year_2008/month_06/day_19/scoreboard.xml');
$result = xml2array($contents, 1);
for($i=0;$i<=20;++$i){
print_r($result['scoreboard']['go_game'][$i]['game']['attr']['league']);
print_r($result['scoreboard']['go_game'][$i]['game']['attr']['status']);
print_r($result['scoreboard']['go_game'][$i]['game']['attr']['start_time']);
print_r($result['scoreboard']['go_game'][$i]['team'][0]['attr']['name']);
print_r($result['scoreboard']['go_game'][$i]['team'][0]['gameteam']['attr']['R']);
print_r($result['scoreboard']['go_game'][$i]['team'][0]['gameteam']['attr']['H']);
print_r($result['scoreboard']['go_game'][$i]['team'][0]['gameteam']['attr']['E']);
print_r($result['scoreboard']['go_game'][$i]['team'][1]['attr']['name']);
print_r($result['scoreboard']['go_game'][$i]['team'][1]['gameteam']['attr']['R']);
print_r($result['scoreboard']['go_game'][$i]['team'][1]['gameteam']['attr']['H']);
print_r($result['scoreboard']['go_game'][$i]['team'][1]['gameteam']['attr']['E']);
echo "

";
}
Reply to this.
jlcfly at 28 Jun, 2008 06:25
If you know the structure, but don't know how many nodes there might be, here's a way to read them without too much difficulty. You can adapt for your own purposes.

XML:

<?xml version="1.0" encoding="utf-8" ?>
<photos>
<photo>
<title>Photo 1</title>
<image>photo1.jpg</image>
</photo>
<photo>
<title>Photo 2</title>
<image>photo2.jpg</image>
</photo>
</photos>


PHP:

$xml = file_get_contents("photos.xml");
$arr = xml2array($xml);

$moreThanOne = true;
while(list($ix) = each($arr['photos']['photo'])) {
if (is_numeric($ix))
echo $arr['photos']['photo'][$ix]['title']['value'] . '<br/>';
else {
$moreThanOne = false;
break;
}
}

if (!$moreThanOne)
echo $arr['photos']['photo']['title']['value'] . '<br/>';
Reply to this.
Felipe at 04 Aug, 2008 08:55
Dear friends,
To deal with accents, I have been using the following function, which converts the characters from XML file into HTML format. Hope it helps.

function replace_accents_html($str){
$array1 = array("á", "à", "â", "ã", "ä", "é", "è", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");
$array2 = array("á", "à", "â", "ã", "ä", "é", "à", "ê", "ë", "í", "ì", "î", "ï", "ó", "ò", "ô", "õ", "ö", "ú", "ù", "û", "ü", "ç", "Á", "À", "Â", "Ã", "Ä", "É", "È", "Ê", "Ë", "Í", "Ì", "Î", "Ï", "Ó", "Ò", "Ô", "Õ", "Ö", "Ú", "Ù", "Û", "Ü", "Ç");

foreach($array2 as $key => $val)
{
$array2[$key] = htmlentities($val);
}
return str_replace($array1,$array2,$str);
}
Reply to this.
moose at 07 Aug, 2008 08:54
Just wanted to say very well written. thanks
Reply to this.
CV at 13 Aug, 2008 11:21
And it works also in older versions of php. I've tried it with 4.4.9 and 5.2.6.
Thanks a lot, this is the best around.
Reply to this.
Forge at 16 Aug, 2008 03:38

Just to help newbies out, if you're pulling an RSS feed down and putting it through this function, heres how to display the RSS items: ($items contains the array returned by the function)

for ($i=0;$i<count($items['rss']['channel']['item']);$i++) {

$itemtitle=$items['rss']['channel']['item'][$i]['title']['value'];
$itemlink=$items['rss']['channel']['item'][$i]['link']['value'];
$itemdesc=$items['rss']['channel']['item'][$i]['description']['value'];

do something here with these variables, like echo them

}

Reply to this.
Samuel Prasetya at 25 Aug, 2008 04:38
i'm impressed, deeply impressed. this function is very useful, damn good stuff. thank you for sharing.
Reply to this.
nacho at 02 Sep, 2008 07:01
CHAVON, SOS UN GROSSO, esta libreria es lo más. (you're simple great man! this is the best library)
Reply to this.
Kellen Green at 04 Sep, 2008 11:35
woops looks like it read the html...

Is there a way to get this function to ignore HTML tags for newsML parsing? it keeps braking up my paragraphs into new array values and cutting off some of the stories. Other then this dilemma excellent script so far.
Reply to this.
Binny V A at 05 Sep, 2008 07:52
Try enclosing the HTML in CDATA tags.
Reply to this.
Leo at 06 Sep, 2008 01:45
Great function - improved my XML parsing a lot ! Thank you !
Reply to this.
Anonymous at 18 Oct, 2008 04:09
Hello,
I have a xml file :
<repeatableElement>
<sub>foo</sub>
<repeatableSub>bar</repeatableSub>
<repeatableSub>foobar</repeatableSub>
</repeatableElement>
<repeatableElement>
<sub>foo2</sub>
<repeatableSub>bar2</repeatableSub>
<repeatableSub>foobar2</repeatableSub>
</repeatableElement>

The script stops at first repeatableElement. How can I do ? I thought to make an array like this but I don't know where to place the code. Can you help me ? Thank you for your function and your help ;)
Array
(
[repeatableElement] => Array
(
[0] => Array
(
[sub] => Array
(
[value] => foo
)
[repeatableSub] => Array
(
[0] => Array
(
[value] => bar
)
[1] => Array
(
[value] => foobar
)
)
)
[1] => Array
(
[sub] => Array
(
[value] => foo2
)
[repeatableSub] => Array
(
[0] => Array
(
[value] => bar2
)
[1] => Array
(
[value] => foobar2
)
)
)
)
)
Reply to this.
Anonymous at 18 Oct, 2008 04:38
it's again me. my xml was malformed, it works now :) sorry for these posts
Reply to this.
Dany at 19 Oct, 2008 02:16
Super! Thank's
Reply to this.
rahul at 23 Oct, 2008 05:26
Truly Amazing dude.like all I would say
"THIS IS THE SIMPLEST AND BEST XML2ARRAY PROGRAM"

Thanks
Reply to this.
Justin Lawrence at 12 Nov, 2008 12:58
Great job!!!! one giant step for PHP and XML!
Reply to this.
ourI.Tguys at 14 Nov, 2008 02:33
THANK YOU! I've been looking for something like this for 2 days ><.
Reply to this.
ourI.Tguys at 14 Nov, 2008 02:35
BTW, your examples are written wrong, they should look like this:
* Examples: $array = xml2array(file_get_contents('feed.xml'));
* $array = xml2array(file_get_contents('feed.xml'), 1, 'attribute');
Reply to this.
Binny V A at 15 Nov, 2008 08:37
My bad - will fix it now.
Reply to this.
Anonymous at 20 Nov, 2008 05:25
My xml not work! What's wrong?
<0>
<name>color</name>
<values>
<0>
<name>Silver</name>
<unlim>1</unlim>
</0>
</values>

</0>
Reply to this.
Binny V A at 11 Mar, 2009 01:29
A tag with just a number, like <0>, is invalid XML. You'll have to change that.
Reply to this.
Bill at 25 Nov, 2008 08:17
This saved me a headache when dealing with XML data with multiple namespaces. Nice work, and I echo Justin Lawrence's enthusiasm.
Reply to this.
Keral Patel at 26 Nov, 2008 07:51
I want to use this for one GPL wordpress plugin.

Can I use it?

Thanks.
Reply to this.
Binny V A at 30 Nov, 2008 09:43
Go right head. And send me the link of the wordpress plugin as well - I use WP in a lot of my sites.
Reply to this.
Vinc at 03 Dec, 2008 05:28
Very Good!

But the function fails if xml file has just one element ....

For instance try

<?xml version="1.0" encoding="UTF-8"?>
<DemoSerie>
<VarName id="PJANT">

<sex id="M">Males
<host>localhost</host>
<dbms>pgsql</dbms>
<database>data2007</database>

<port>5432</port>
<username>user</username>
<pass>pass</pass>
<item>item</item>
<select>select item from table where pro=226 </select>
<source>Demographyc balance</source>
<status>Final</status>
</sex>


<sex id="F">Females
<host>localhost</host>
<dbms>pgsql</dbms>
<database>data2007</database>
<port>5432</port>
<username>user</username>
<pass>pass</pass>

<item>item</item>
<select>select item from table where pro=226 </select>
<source>Demographyc balance</source>
<status>Final</status>

</sex>



</VarName>


<VarName id="LBIRTHST">

<sex id="T">Total
<host>localhost</host>
<dbms>pgsql</dbms>
<database>data2007</database>
<port>5432</port>

<username>user</username>
<pass>pass</pass>
<item>item</item>
<select>select item from table where pro=226 </select>
<source>Census</source>
<status>Final</status>
</sex>
</VarName>
</DemoSerie>

The element sex with Total attribute doesn't appear in the array ....
Any help?

Bye
V
Reply to this.
Binny V A at 05 Dec, 2008 03:08
I think its a bug with my code. I think the problem is caused by loose nodes - like...
<sex id="M">Males
<host>localhost</host>

Here the 'Males' text is a loose node. If possible, put that in a tag. Meanwhile, I'll see if I can fix my code.
Reply to this.
maske at 23 Feb, 2009 08:10
No it's not problem with loses of node. When i have just one element xml2array will lose tag like this [1]=> probably functions don't add tag for counting if you have just 1 element. When i add one more element everything works perfectly!
Reply to this.
maske at 26 Feb, 2009 12:17
I solve this problem with checking array keys (function array_keys) but it would be nice if xml has only one node to be put in array like this
[0]=>array(...). Anyway great function....
Reply to this.
vasya80 at 16 Dec, 2008 08:38
mistakes:

need to add:
line 78
if($attributes_data) $current[$tag][$repeated_tag_index[$tag.'_'.$level].'_attr'] = $attributes_data;
line 79

line 85
if($attributes_data) $current[$tag]['1_attr'] = $attributes_data;
line 86
Reply to this.
Anonymous at 16 Dec, 2008 12:10
There is a error:
when there is the ¡ symbol, this happen:
<?php
...

$xml = " <person>
<name>Peter</name>
<address>5th. ¡Avenue</address>
</person> ";

$ws = xml2array($xml);

...
?>

The result is:

Array
(
[person] => Array
(
[name] => Peter
[address] => 5th.
)

)
Reply to this.
microinfosoft at 19 Dec, 2008 03:27
The parser is really good but there is a big problem as most of the site owner use share hosting account.So when xml file size is large then this parser unable to read the data properly.It is showing memory related error.We can increase the memory limit but as you know hosting provider does not support to use huge resource.I have only 5 mb xml file.I tested it in many server but result is zero.So is there any way to overcome this problem.The work flow of it is...it store all the tag name with its attribute into array which took huge memory.2nd then it store the value into array which took much more memory and processing xml file by php is also taking huge memory.

For processing this 5MB xml file i have changed memory limit to 256 MB but it still showing me memory error.

So can anyone tell me how to over come it....Can we split the xml file into small file or can we parse the xml one record at one time and then next one without storing it into array...

Thanks
Sam
listen and donwload song at online for free
www.hindigan.com
Reply to this.
Binny V A at 23 Dec, 2008 09:37
One possibility is to run the script as a standalone script - don't run it through a web server. Run it as 'php parsexml.php'
Reply to this.
Yousuf Philips at 04 Jan, 2009 12:07
Tried to use the code but all i get is an error line "Fatal error: Cannot create references to/from string offsets nor overloaded objects" on the below line.

$current = &$current[$tag][$last_item_index];

Reply to this.
Xavier Sanz at 04 Feb, 2009 06:45
Hi, i'm trying to use this excellent piece of code with conjunction of svn, if I execute 'svn info --xml', the string is parsed correctly. But if I execute 'svn log --xml' the revision attribute is not parsed correctly into the array.
Reply to this.
Dalefish at 19 Feb, 2009 02:08
I only found this after writing a script of my own (custom to the XML files I'm dealing with) and it failing when using a file of 13MB. Problem here is it needs to be run on the server, execution time can be increased but the files could range anywhere from 2MB to 15+ so I really want to plan for an unknown file size. I'm going to work on the idea of automated splitting of the file before parsing, but any suggestions would be appreciated.
Reply to this.
EvanFell at 27 Feb, 2009 03:54
A few comments up vasya80 posted a couple lines of code.

The problem he is attempting to fix is one of getting attributes from tags. XML2ARRAY does not handle attributes well and will actually only pull attributes for the first two children of a category, beyond that they are just null. Vasya80's code is a step in the right direction but does not completely solve the issue. I have been working on it, but haven't got it 100% yet. When I do I'll post my results. I am using XML2ARRAY on some very complex XML data sets, it is a great bit of code, just not perfect, yet :)!

-Evan
Reply to this.
sangram2681 at 09 Mar, 2009 04:48
Hello my xml file is having text as follows
1)
<?xml version="1.0" encoding="iso-8859-1"?><JASON><firstName>John</firstName><lastName>Smith</lastName><streetAddress>21 2nd Street</streetAddress><city>New York</city><state>NY</state><postalCode>10021</postalCode>
<phoneNumbers>
<0>212 555-1234</0>
<1>646 555-4567</1>
</phoneNumbers>
</JASON>
2)I am using Xml2Array for conversion but my output doesn't accurate as i expected

Output:
Array ( [JASON] => Array ( [firstName] => John [lastName] => Smith [streetAddress] => 21 2nd Street [city] => New York [state] => NY [postalCode] => 10021 [phoneNumbers] => Array ( ) ) )

Quick Note:
It Misses phoneNumber
I am trying to solve it but meanwhile if any one got clue please let me to know by this forum.

Thanks In advance...
Reply to this.
Binny V A at 11 Mar, 2009 01:30
A tag with just a number, like <0>, is invalid XML. You'll have to change that.
Reply to this.
kraiosis at 09 Mar, 2009 01:53
HELP!
i have this xml with ONE item
<?xml version="1.0" encoding="iso-8859-1" ?>
<parentElement>
<childElement></childElement>
<childElement></childElement>
<item amount="1" code="CODE" description="Some Description">
<memo></memo>
<suplier code="1" name="AMAZON"/>
</item>
</parentElement>
/////////////////////////////// OR THIS WITH TWO ITEMS
<?xml version="1.0" encoding="iso-8859-1" ?>
<parentElement>
<childElement></childElement>
<childElement></childElement>
<item amount="1" code="CODE" description="Some Description">
<memo></memo>
<suplier code="1" name="AMAZON"/>
</item>
<item amount="1" code="CODE" description="Some Description">
<memo></memo>
<suplier code="1" name="AMAZON"/>
</item>
</parentElement>
//////////////////////////////////////////
when trying ro read it with xml2array works fines only if i have more than one item. But when reading xml file with only one item it doesnt read the item alone.

here is my parser:

if(file_exists("order.xml")){

$contents = file_get_contents("order.xml");

$result = xml2array($contents, 1);

if($result['parentElement']!=''){
echo $result['childElement'];


/*
for ($i=0;$i<count($result['parentElement']['item']);$i++) {

echo $result['parentElement']['item'][$i]['amount'];
echo $result['parentElement']['item'][$i]['code'];
echo $result['parentElement']['item'][$i]['description'];
echo $result['parentElement']['item'][$i]['memo']['value'];

}
}

}
Reply to this.
kraiosis at 13 Mar, 2009 03:15
SOLVED! This wotks for xml2array() when having only one record on the xml

$items = $result['parentElement'']['item'];

if(is_array($items[0])){

$i = 0;
echo $result['parentElement']['item'][$i]['amount'];
echo $result['parentElement']['item'][$i]['code'];
echo $result['parentElement']['item'][$i]['description'];
echo $result['parentElement']['item'][$i]['memo']['value'];
$i++;

}else{

echo $result['parentElement']['item']['amount'];
echo $result['parentElement']['item']['code'];
echo $result['parentElement']['item']['description'];
echo $result['parentElement']['item']['memo']['value'];

}
Reply to this.
kraiosis at 13 Mar, 2009 03:16
Sorry i forgot to include the while

just nets to $i =0;
put: while($result['pedido']['articulo'][$i]['attr']['cantidad']!="") {

and then next to: $i++;
close the while with }
Reply to this.
Anonymous at 16 Mar, 2009 07:15
Very nice work!

Thanks so much for a release to the public.


This has been very helpful to me!

Keep up the good codes, your headed for greatness! :-)

Reply to this.
Anonymous at 06 Apr, 2009 03:45
Hello and thank you, this script is excellent and I use it in a variety of ways. One way is to parse a Yahoo MRSS feed.

search.yahoo.com/mrss/

Unless your script does this (and I missed it) please suggest how, one thing this script seems to lack is the ability to grab the attributes for an tag item. Such as

<media:content url="xyz.jpg" medium="image" fileSize="2010393" type="image/jpeg">
<media:title>Image Title</media:title>
<media:description>Image Description</media:description>
<media:credit>Image Credit</media:credit>
</media:content>

I would love to be able to use the attributes of the media:content tag. The URL is especially important to me at this point.

Thanks.
Anonymous
Reply to this.
Anonymous at 06 Apr, 2009 03:56
I did notice above some people trying to figure this out. Not sure what the issue is, but here is my 2 cents...

Basically split on the spaces, then save the attributes to a array called attributes.

array(7) {
["title"]=> "Title of the Item"
["category"]=> "Feature"
["pubDate"]=> "Fri, 16 Jan 2009 14:13:29 PST"
["link"]=> "URL of the news item"
["guid"]=> "12345678901"
["description"]=> "Description of the news item"
["media:content"]=>
&array(4) {
["attributes"]=>
&array(4) {
["url"]=> "xyz.jpg"
["medium"]=> "image"
["fileSize"]=> "2010393"
["type"]=> "image/jpeg"
}
["media:title"]=> "Image Title"
["media:description"]=> "Image Description"
["media:credit"]=> "Image Credit"
}
}

Reply to this.
arajcany at 08 Apr, 2009 06:22
This is a great function! worked straight out of the box for a Picasa album feed. I am going to use it to insert images into Wordpress posts on the fly. Thanks heaps and well done. Andrew.
Reply to this.
Anonymous at 14 Apr, 2009 02:22
Funny after poking around and around I realize it does grab attributes... gotta change 0 to a 1... Or read the documentation.

Thanks!
Reply to this.
Glen at 16 Apr, 2009 10:32
I've been using the same xml parsing script for many years and after tesing yours I realized how inefficient mine was. It was like night and day.

I did however convert it into a php Class along with a few other minor changes before using it in my scripts.

Thanks for sharing it with the community.
Reply to this.
Jeissy at 03 May, 2009 11:56
WOW! this is what i need! It's working straight away!
Great job!!!
Thanks for sharing :-)
Reply to this.
Tuning at 06 May, 2009 10:02
Very good job!
Thank you.

I just need a small help. I have the following feed:
xmlfeed.laterooms.com/index.aspx?aid=5415&rtype=3&lang=it&hids=153198

If I do...
print_r($array['hotel_search']['hotel']['images']);
... then there is nothing in the array, but if I check the feed manually, I see more than one content in the images.

Could you help?
Reply to this.
Anonymous at 25 May, 2009 07:24
Hi,

in forex.xml file there is no any tag for convert into RUB can u provide us XML to to convert into RUB

Regards
Anuj
Reply to this.
hsaturn at 07 Jul, 2009 08:29
Hello,

I'm answering to all people here that have the one or multiple item problem first related in the 6th comment by Anonymous at 30 Jul, 2007 01:44 (The message array).

The basic idea of my patch is that we know the xml schema.
So we just send an additionnal array to the function where we want ... arrays.
In the 'message' xml example, we send an additionnal array('message') so the xml2array function will now
output an array, even if there is only one 'message' item.

The modifications are (See the patch right after this post)

1/ function xml2array($contents, $get_attributes=1, $priority = 'tag', $array_force=array())
2/ if($type == "open") {//The starting of the tag '<tag>'
$parent[$level-1] = &$current;
if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
if (in_array($tag,$array_force))
$current[$tag][0] = $result;
else
$current[$tag] = $result;
if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
$repeated_tag_index[$tag.'_'.$level] = 1;

if (in_array($tag,$array_force))
$current = &$current[$tag][0];
else
$current = &$current[$tag];


This patch counts correctly the number of message item in the following xml samples (6th comment)
--------------------
<messageList>
<message>
<from>2</from>
<to>1</to>
<text>adf</text>
</message>
<message>
<from>3</from>
<to>4</to>
<text>bla adf</text>
</message>
</messageList>

--------------------------
<messageList>
<message>
<from>2</from>
<to>1</to>
<text>adf</text>
</message>
</messageList>
-----------------------
Reply to this.
barca at 09 Jan, 2010 07:41
I couldn't just use your fix and close this website. You can't imagine how happy I am with this. This is the best XML to ARRAY function, indeed. But with that "single/multiple" issue it was useless for me. THANKS A LOT for your job. Maybe you have a BIGGER investment into this script than the owner. Thanks again.
Reply to this.
hsaturn at 07 Jul, 2009 08:31
Save this as diff.path, binny's code as xml.php then patch using the following command (linux)
> patch xml.php < diff.path

----------[ diff.path file content ]-----------
12c12
< function xml2array($contents, $get_attributes=1, $priority = 'tag') {
---
> function xml2array($contents, $get_attributes=1, $priority = 'tag', $array_force=array()) {
66a67,69
> if (in_array($tag,$array_force))
> $current[$tag][0] = $result;
> else
70a74,76
> if (in_array($tag,$array_force))
> $current = &$current[$tag][0];
> else
134a141
> ?>
-------------[ end of diff.patch ]-------------
Reply to this.
AndyKnas at 20 Jul, 2009 06:29
I used this function in the past and see that it's been updated, and fixes an issue with a single element but I can't get the diff to work. can someone post the whole function, with the fix?
Reply to this.
AndyKnas at 20 Jul, 2009 06:51
...I think I have the coding adjusted, but I still don't get back the expected results.

I would expect to get the same results with this code for either of your xml snippets.

$xmlresult = xml2array($yourXML);
$from=$xmlresult['messageList']['message'][0]['from'];
Reply to this.
DavidPFarrell at 13 Jul, 2009 04:21
Sweet function - thanks for sharing!

I found that the function treats empty 'complete' tags as arrays:

i.e. <mytag/> is turned into [mytag] => array()

for my application, I prefer to have empty strings in these cases.

So I made the following small modification:

...
} elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
// Treat empty array as empty string instead
if (is_array($result) and count($result) == 0) $result = '';
...

Thanks again!
Reply to this.
LD at 31 Jul, 2009 11:16
Hey Man,
If I want to get only the second level schema into the array how can I do it?
My schema looks like
<item>
<sub item1>
<sub item2>
<item/>


Reply to this.
Bjarne at 10 Aug, 2009 02:20
Excellent!!!

There is an error in the second example:

$array = xml2array(file_get_contents('feed.xml', 1, 'attribute'));

Should be:

$array = xml2array(file_get_contents('feed.xml'), 1, 'attribute');
Reply to this.
Dizz at 10 Aug, 2009 04:29
Hi,
This is turning every tag into an array, How can I fix this.?
Reply to this.
krebs at 15 Aug, 2009 02:25
thanks!
Reply to this.
paulrajj at 17 Aug, 2009 02:52
hi i am a beginner in php. i am having the problem when i am getting the tag values as array. i am getting the url values as output which is having the & operator in query string. for that i have tried with htmlspecialchars() and htmlentites() but it didnt return any value. in which line i have give this, to fix this problem. thanks.
Reply to this.
Ryan Mitchell at 18 Aug, 2009 05:36
Brilliant! Thank you so much for writing this -- it really saved me (and I'm sure many others) a ton of pointless work. Worked beautifully "out-of-box"!
Reply to this.
Eugene at 29 Aug, 2009 02:32
thx man,
works like a dream!!!!!!!!!
sanitize data for better use..
It will be Brilliant if u will include module to use BIIIIG xml files
chao
Reply to this.
Oleksandr Balyuk at 01 Sep, 2009 01:38
This is truly the best XML parser. Excellent job! Thank you very much!
Reply to this.
Dhaval at 02 Sep, 2009 03:58
Hello,

I have one problem with this function.
my xml code looks like

<response>
<status_code>0</status_code>
<results>http://xyz.com/index.php?code=abcdef&dp=11&u=123456</results>
</response>

now I pass this value into xml2array function and it returns

Array
(
[response] => Array
(
[status_code] => 0
[results] => xyz.com/index.php?code=abcdef
)
)


IT DOESN'T RETURN OTHER QUERY STRING PARAMETERS.

How do I solve this?

Thanks & Regards,

Dhaval
Reply to this.
Anonymous at 06 Sep, 2009 01:36
the one thing i am having trouble with is the format of the array is different depending on if an element has 1 or more than 1 children.

for example:

<book>
<author>Bob Jones</author>
</book>

<book>
<author>Bob Jones</author>
<author>Steve Smith</author>
</book>

returns:

array[book][author] = bob Jones

and

array[book][author][0] = bob jones
array[book][author][1] = steve smith

makes things difficult because in my application the number will be different for every user.

any words of advice?
Reply to this.
Karlheinz at 22 Sep, 2009 10:55
To anonymous, r.e.

array[book][author] = bob Jones

vs.

array[book][author][0] = bob jones
array[book][author][1] = steve smith


I doubt that there is a way to get around this, nor would you want to. The only solution would be if the function ALWAYS gave an array for author, i.e.

array[book][author][0] = bob Jones

But, how would the function know if you wanted to have [author] be an array? It would make calling the function horribly complicated, which kind of defeats the purpose.

The solution, I think, is to check if the returned value is an array. That is,

if is_array($array['book']['author']) {
foreach ($array['books']['author'] as $index => $name){
print "$name
\n";
}
else {
print $array['book']['author'] . "
\n";
}


Hope that helps.
Reply to this.
Karlheinz at 22 Sep, 2009 10:57
Okay, apparently the "code" tag in the comments doesn't keep white space or strip out break tags, so my code above is not easy to read. Hopefully you get the gist.
Reply to this.
Robbie at 04 Dec, 2009 08:38
I simply did this to workaround this issue:

$contents = @file_get_contents($database);
$input = xml2array($contents);

if (!$input[form][field][0]) {
// restructure the fields to compensate if there's only one.
$input[form][temp] = $input[form][field];
unset($input[form][field]);
$input[form][field][0] = $input[form][temp];
unset($input[form][temp]);
}
Reply to this.
Robbie at 04 Dec, 2009 08:39
I think I misunderstood your question; mine was to fix the fact that if there was only one element, it was not giving it an array key of [0].

Sorry; wrong answer & no delete button :)
Reply to this.
Anz at 17 Sep, 2009 08:51
Great work
Reply to this.
Nico at 21 Sep, 2009 07:16
Thanks a lot for that very helpfull work.
Despite I've the same pb as pk about
"Fatal error: Cannot use string offset as an array in"
and more, It hangs my Apache with with trace in Apache log
[error] [client 127.0.0.1] PHP Notice: Array to string conversion in C:\\www\\myapp\\cat4.php on line 92 ( this line corresponds to "$current[$tag] = $result;" in tag treatment )
[error] [client 127.0.0.1] PHP Stack trace:
[error] [client 127.0.0.1] PHP 1. {main}() C:\\www\\myapp\\cat4.php:0
[error] [client 127.0.0.1] PHP 2. xml2array() C:\\www\\myapp\\cat4.php:203
[notice] Parent: child process exited with status 3221225477 -- Restarting.
I'm under Apache2 and PHP 5.3.0, WinXP
Calling function with 1 and 'tag' options

Do you have an idea ?
Thanks again for all
Nico, France
Reply to this.
Lester at 04 Oct, 2009 12:53
Hello:

Please excuse me for asking such a newbie question but I am having a difficult time getting the attributes. Can someone please help me? Here's an example of my XML:

<result>
<content-sources>
<content-source friendly-name="Google" engine-original-position="5">
</content-source>
<content-source friendly-name="Bing" engine-original-position="2">
</content-source>
<content-source friendly-name="Yahoo! Search" engine-original-position="5">
</content-source>
</content-sources>
<site-link>
www.mysite.com/mcdonalds.html
</site-link>
<paid>false</paid>
<display-url>http://www.mysite.com</display-url>
<title>McDonalds</title>
<description>About McDonalds</description>
</result>
<result>
<content-sources>
<content-source friendly-name="Ask" engine-original-position="2">
</content-source>
<content-source friendly-name="Overture" engine-original-position="3">
</content-source>
<content-source friendly-name="Miva" engine-original-position="4">
</content-source>
</content-sources>
<site-link>
www.mysite.com/burgerking.html
</site-link>
<paid>false</paid>
<display-url>http://www.mysite.com</display-url>
<title>Burger King</title>
<description>About Burger King</description>
</result>

...........

Can someone please illustrate how to parse and display the XML into HTML but most importantly, include the attributes? I'm hoping to get some HTML/TXT that looks like this:

Result #1: McDonalds - Found on Google (5), Bing (2) Yahoo Search (5)
Description: About McDonalds

Result #2: Burger King - Found on Ask (2), Overture (3), Miva (4)
Description: About Burger King

..............

I tried my best but here's my success in printing everything BUT the attributes:

require("xml2array.php");
include("Snoopy.class.php");

$url = "http://mysite.com/mytest.xml;
$snoopy = new Snoopy;
$snoopy -> fetch($url);
$data = $snoopy -> results;
$data = str_replace("&", "&", $data);
$parse = xml2array($data, 1);

$results = $parse["search-results"]["collection"]["group"]["group"]["result"];

$i = 0;
foreach($results as $row) {
$title = $row["title"];
$url = $row["site-link"];
$description = $row["description"];

echo <<<EOFHTML

$title

$url

$description

<hr>

EOFHTML;
}

?>

...........

Can someone please assist me with getting the attributes, such as the friendly name and engine original position for every content source in the sample XML above?

Thank you greatly. Much appreciated.

Lester
Reply to this.
Dhaval at 16 Oct, 2009 03:17
Hello,

Can any one please tell me why "&" character is not working in xml2array function?

Thanks & Regards,
Dhaval
Reply to this.
RDeelstra at 23 Oct, 2009 03:08
Very nice function! Thank you for sharing :)

Kind regards
Reply to this.
Anonymous at 06 Nov, 2009 07:00
Hello,

When parsing a very big XML it gives a white scree..any solution?

S
Reply to this.
Skipy at 13 Nov, 2009 07:54
This is really good XML parser. thx
Reply to this.
Anonymous at 18 Nov, 2009 04:54
Thanks a lot man!!!!!! you saved my life
Reply to this.
Anonymous at 24 Nov, 2009 07:00
The code seems to stop reading (or enter an infinite loop?) when it sees a & character. Is there a fix for this?
Reply to this.
Anonymous at 01 Dec, 2009 08:26
<a vr1="01" rel="nofollow">
<B vr1="02">
<BB vr1="03" />
</B>
<B vr1="04">
<BB vr1="05" />
</BB>
</A>


<?php

$result ='<a vr1="01" rel="nofollow"><B vr1="02"><BB vr1="03" /></B><B vr1="04"><BB vr1="05" /></BB></A>';


$arrayData = xml2array($result);
//-------------------------------------
print_r($arrayData);
?>

Array ( [A] => Array ( [B] => Array ( [0] => Array ( [BB] => Array ( ) [BB_attr] => Array ( [vr1] => 03 ) ) [1] => Array ( [BB] => Array ( ) [BB_attr] => Array ( [vr1] => 05 ) ) [0_attr] => Array ( [vr1] => 02 ) ) ) [A_attr] => Array ( [vr1] => 01 ) )

Where is vr1=04 ?
Reply to this.
Sarath DR at 02 Dec, 2009 09:51
Thanks man !!...It helped me a lot..thank you very much.
Reply to this.
Robbie at 04 Dec, 2009 08:41
My XML file may contain \n characters...

Eg.

<testimonial>Hi there,
I like this site.

Keep up the great work!</testimonial>

Anyone have a workaround to xml2array stripping the carriage returns? When loaded, xml2array gives me: "Hi there,I like this site.Keep up the great work!"

Thanks!
Reply to this.
Robbie at 04 Dec, 2009 09:00
Looks like it happens right at xml_parse_into_struct but can't find support for what I want to do... so I think to workaround it I'll place a special code ... like [br] in my xml output and have it convert it back to a \n upon load. Wouldn't work if I needed direct access to the xml (with an aggregator, for example). Any suggestions? Thanks!!
Reply to this.
Amirhossein at 10 Dec, 2009 01:29
how can i extract attributes to a variable?

<node>
<name id=100> </name>

</node>
i want 100
how can i doing it?
thanks
Reply to this.
GSNet at 15 Jan, 2010 09:24
echo $array['node']['name']['attr']['id'];
Reply to this.
e_i_pi at 20 Dec, 2009 07:12
Wow, all I have to say is wow. This is -the- best xml->array parser out there - readers, if you don't believe me, go through what i've been through. I have been searching the net for about 5-6 months for upgrades to each xml2array() I have implemented, and gone through changing my code every time. I'm settling here. This is exactly what I need. The naming schema in the resultant array is intelligent, succinct, and standardised. What's more, the attributes are stored neatly in a standardised manner, and do not require lumberous code to navigate to them. Hats off to the coder, well done :)
Reply to this.
Exter at 07 Jan, 2010 06:24
THANKS!
Reply to this.
Anonymous at 18 Jan, 2010 12:57
It's very good. I've written something almost identical in flash. Then I found this. It's a saviour!
Reply to this.
André at 20 Jan, 2010 04:56
Thank you very very very much!!!!!!!

I say very?????

Reply to this.
Anonymous at 27 Jan, 2010 05:50
LOVE IT.. thank you very much
Reply to this.
C0C1 at 30 Jan, 2010 05:21
Hello, I have a very weird question. I read the comments but not answered anybody...
why the last tag has 1 key? How should I fix it?
this questioned earlier by:
LT at 08 May, 2008 07:18
Anonymous at 01 Dec, 2009 08:26

(
[playlist] => Array
(
[song] => Array
(
[0] => Array
(
[file] => ./song1.mp3
[title] => title1
[artist] => artist01
)

[1] => Array
(
[file] => ./song2.mp3
[title] => title2
[artist] => artist02
)

[2] => Array
(
[file] => ./song3.mp3
)

)

)

)

where are the followings?
[title] => title3
[artist] => artist03

thanks a lot!
Reply to this.
C0C1 at 30 Jan, 2010 05:34
well, I left the structure of my xml:
<?xml version="1.0" encoding="UTF-8" ?>
<playlist>
<song>
<file>./song1.mp3</file>
<title>title1</title>
<artist>artist01</artist>
</song>
<song>
<file>./song2.mp3</file>
<title>title2</title>
<artist>artist02</artist>
</song>
<song>
<file>./song3.mp3</file>
<title>title3</title>
<artist>artist03</artist>
</song>
</playlist>
Reply to this.
Anonymous at 19 Feb, 2010 09:55
This is working pretty well. I'm using it to parse tweet xml but it's not liking the '&'. Such as in a node <time_zone>Eastern Time (US & Canada)</time_zone>
Reply to this.
Anonymous at 14 Mar, 2010 05:05
Really fentastic it is very usefull to me. Thanks a lot
Reply to this.
Mike at 17 Mar, 2010 01:41
Any Idea when I move from a Windows environment to a hosted Linux environment it seems to not work for me?

In Windows it works, I upload to my server (Linux) it doesn't. Any ideas?
Reply to this.
Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed