xml2array() - XML Parser for PHP
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($parser, XML_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($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($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($tag, array_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
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!
anywhere.
$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);
Thanks
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>
zzzzz.
</Tekst>
$contents,0 gives : Array ( [p] => xxxxx. )
$contents gives : Array ( [p] => Array ( [value] => xxxxx. [attr] => Array ( [align] => justify ) ) )
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.
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.
See my solution to that problem
by searching hsaturn at 07 Jul, 2009 08:29
} 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!
by searching hsaturn at 07 Jul, 2009 08:29
if(isset($value)) $result['value'] = utf8_decode($value);
great piece of coding!
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.
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">
In the result array it should look like: home[id], home[price], home[available] etc.
Best function i found in the net..
Greetz from Germany and thanks a lot!
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
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.
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
.
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;
}
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!
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
)
// Mikael from Sweden
thanks
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
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.
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 "
";
}
}
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>
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.
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?
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.
It's really working :)
} 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!
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
:(
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
$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 "
";
}
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/>';
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);
}
Thanks a lot, this is the best around.
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
}
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.
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
)
)
)
)
)
"THIS IS THE SIMPLEST AND BEST XML2ARRAY PROGRAM"
Thanks
* Examples: $array = xml2array(file_get_contents('feed.xml'));
* $array = xml2array(file_get_contents('feed.xml'), 1, 'attribute');
<0>
<name>color</name>
<values>
<0>
<name>Silver</name>
<unlim>1</unlim>
</0>
</values>
</0>
Can I use it?
Thanks.
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
<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.
[0]=>array(...). Anyway great function....
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
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.
)
)
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
$current = &$current[$tag][$last_item_index];
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
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...
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'];
}
}
}
$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'];
}
just nets to $i =0;
put: while($result['pedido']['articulo'][$i]['attr']['cantidad']!="") {
and then next to: $i++;
close the while with }
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! :-)
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
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"
}
}
Thanks!
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.
Great job!!!
Thanks for sharing :-)
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?
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
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>
-----------------------
> 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 ]-------------
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'];
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!
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/>
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');
This is turning every tag into an array, How can I fix this.?
works like a dream!!!!!!!!!
sanitize data for better use..
It will be Brilliant if u will include module to use BIIIIG xml files
chao
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
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?
array[book][author] = bob Jonesvs.
array[book][author][0] = bob jonesarray[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 JonesBut, 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.
$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]);
}
Sorry; wrong answer & no delete button :)
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
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
Can any one please tell me why "&" character is not working in xml2array function?
Thanks & Regards,
Dhaval
Kind regards
When parsing a very big XML it gives a white scree..any solution?
S
<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 ?
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!
<node>
<name id=100> </name>
</node>
i want 100
how can i doing it?
thanks
I say very?????
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!
<?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>
In Windows it works, I upload to my server (Linux) it doesn't. Any ideas?
a, strong, em, b, i, code, pre, pandbrallowed. Other tags will be shown as code(< will become <). Urls, Line breaks will be auto-formated.