Thursday, January 6, 2011

PHP: Store XML file into an Array

Example XML file: (test.xml)

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


Example PHP file:
function xml2array($xml) {
$xmlary = array();

$reels = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*)<\/\s*\\1\s*>)/s';
$reattrs = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';

preg_match_all($reels, $xml, $elements);

foreach ($elements[1] as $ie => $xx) {
$xmlary[$ie]["name"] = $elements[1][$ie];

if ($attributes = trim($elements[2][$ie])) {
preg_match_all($reattrs, $attributes, $att);
foreach ($att[1] as $ia => $xx)
$xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
}

$cdend = strpos($elements[3][$ie], "<");
if ($cdend > 0) {
$xmlary[$ie]["text"] = substr($elements[3][$ie], 0, $cdend - 1);
}

if (preg_match($reels, $elements[3][$ie]))
$xmlary[$ie]["elements"] = xml2array($elements[3][$ie]);
else if ($elements[3][$ie]) {
$xmlary[$ie]["text"] = $elements[3][$ie];
}
}
return $xmlary;
}

$file = "test.xml";

// replace spacing to a space character
$space = strrpos($file, " ");
if ($space === false) {
// not found
}else {
$file = str_replace(" ", "%20", $file);
}

//Get the XML document loaded into a variable
$xml = file_get_contents($file);
echo '<pre>' . print_r(xml2array($xml), true) . '</pre>';
Refer ASCII code / HTML code / Hex / Special Code / Virtual Key Codes @ here.

Output:
Array
(
[0] => Array
(
[name] => note
[text] => 
[elements] => Array
(
[0] => Array
(
[name] => to
[text] => Tove
)

[1] => Array
(
[name] => from
[text] => Jani
)

[2] => Array
(
[name] => heading
[text] => Reminder
)

[3] => Array
(
[name] => body
[text] => Don't forget me this weekend!
)

)

)

)

Reference:
PHP XML 2 Array Function
XML to Array and backwards

2 comments:

  1. This is a nice article..
    Its very easy to understand ..
    And this article is using to learn something about it..

    c#, dot.net, php tutorial, Ms sql server

    Thanks a lot..!

    ReplyDelete