PHP: Convert XML to Object
Hey there.
Glad to see our website movement has increased, but you people aren't posting as much as we'd like you to.
Today we're going to provide you with a cool simple function to convert a XML string (from a file) to an object.
This is very useful for people running PHP4 that can't use simplexml_load_string
Please note this function doesn't support attributes on xml files.
Glad to see our website movement has increased, but you people aren't posting as much as we'd like you to.
Today we're going to provide you with a cool simple function to convert a XML string (from a file) to an object.
This is very useful for people running PHP4 that can't use simplexml_load_string
- Code: Select all
<?php
function parseXMLtoObject($xml) {
$obj = new stdClass();
$xml = explode("\n",$xml);
$main_n = '';
foreach ($xml as $x) {
$first_n = false;
$close_n = false;
if ($x != '') {
$start_val = (strpos($x,">")+1);
$end_val = strrpos($x,"<") - $start_val;
$start_n = (strpos($x,"<")+1);
$end_n = strpos($x,">") - $start_n;
$n = strtolower(substr($x,$start_n,$end_n));
if (substr_count($x,"<") == 1) {
if (!empty($main_n) && !stristr($n,"/")) {
$submain_n = $n;
$first_n = true;
} else {
$main_n = $n;
$submain_n = '';
$first_n = true;
}
}
if (!empty($submain_n) && stristr($submain_n,"/")) {
$submain_n = '';
$first_n = false;
$close_n = true;
}
if (!empty($main_n) && stristr($main_n,"/")) {
$main_n = '';
$submain_n = '';
$first_n = false;
$close_n = true;
}
$value = substr($x,$start_val,$end_val);
if (!$close_n) {
if (empty($main_n)) {
$obj->$n = $value;
} else {
if ($first_n) {
if (empty($submain_n)) {
$obj->$main_n = new stdClass();
} else {
$obj->$main_n->$submain_n = new stdClass();
}
} else {
if (!empty($value)) {
if (empty($submain_n)) {
$obj->$main_n->$n = $value;
} else {
$obj->$main_n->$submain_n->$n = $value;
}
}
}
}
}
}
}
return $obj;
}
?>
Please note this function doesn't support attributes on xml files.