0

I have this string..

'<tag k="addr:country" v="UY"/>'

I want make that string into an array like

array(
   "k" => "addr:country",
   "v" => "UY"
)

I planning to explode by ' ' and explode it again by charater '=' and form the array, but I dont think that is a good code. I am wondering if there is a better way of extracting the attribute from the string.

Thanks in advance/

Eddie
  • 26,593
  • 6
  • 36
  • 58
  • 1
    I'm sure there's a really REALLY complex regex that could help you achieve this, but if "k" and "v" are going to be statically located in the string in the same pattern, I'd recommend just using substrings to locate k and v and extract their respective values. – Ye. Apr 25 '15 at 05:06
  • 1
    possible duplicate of [How do you parse and process HTML/XML in PHP?](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – Mark Miller Apr 25 '15 at 05:07
  • 1
    PLEASE don't try to parse XML by splitting strings. – Stephen Apr 25 '15 at 05:51

1 Answers1

1

You could use SimpleXML:

$input = '<doc><tag k="addr:country" v="UY"/></doc>';

$xml = simplexml_load_string($input); 
foreach($xml->tag[0]->attributes() as $a => $b) {
    print "$a => $b \r\n";
}

This would return

k => addr:country 
v => UY 
Huey
  • 5,110
  • 6
  • 32
  • 44
  • I tried this one earlier and i'm getting Call to a member function attributes() on a non-object in – Eddie Apr 25 '15 at 05:12