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/

3
  • 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. Commented Apr 25, 2015 at 5:06
  • 1
    possible duplicate of How do you parse and process HTML/XML in PHP? Commented Apr 25, 2015 at 5:07
  • 1
    PLEASE don't try to parse XML by splitting strings. Commented Apr 25, 2015 at 5:51

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this one earlier and i'm getting Call to a member function attributes() on a non-object in

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.