BobR BobR - 11 months ago 55
PHP Question

Parsing fields and values from an XML file using PHP

I am trying to find a way to get fields and values reading a file. The file is constructed similar to an XML so its like this..

<tag field1="value1" field2="value2" field3="value3" .... />
<tag2 field5="value5" field6="value6" field7="value7" ... />

<tagn .... />

If I only interested in only one specific tag (e.g. the first one), how can I easily get the fields and values from that line ?

Here is what I have managed to do, but there may be an easier way since the file is XML constructed ?

function string2KeyedArray($string, $delimiter = '" ', $kv = '=') {
if ($a = explode($delimiter, $string)) { // create parts separated by a " + space
foreach ($a as $s) { // each part
// Removing the known tag name
$s = str_replace("tag ","",$s);
//removing the starting < and the ending />
$s = str_replace("<","",$s);
$s = str_replace(">","",$s);
$s = str_replace("/","",$s);
//removing the " from the value
$s = str_replace("\"","",$s);
if (strpos($s,"=")) {
if ($pos = strpos($s, $kv)) { // key/value delimiter
$ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv)));
} else { // key delimiter not found
$ka[] = trim($s);
return $ka;

$string ='<tag field1="value1" field2="value2" field3="value3" />'
$fields = string2KeyedArray($string);

//Which returns what I am looking for

Answer Source

Sorry for the late reply. The file i wanted to read was indeed an XML file and i used XML Parser at the end to store in the database. Thanks for the heads up.