user1464409
user1464409

Reputation: 1042

How to convert a Python List to a PHP array via a MySQL table

I have inherited a MySQL database where one of the fields in a table returns a string that was once a Python list so I get something like this:

$test = "[u'Person 1', u'Person 2']";

What is the cleanest/easiest/best/simplest (I'm not sure how to phrase this) to get this data back into an array in PHP? I am using PHP4 but I could upgrade to PHP5.4 if necessary.

I don't have much experience programming in PHP and my first thought was to do something like this:

$new = explode(",",$test);

This kind of works but it would need cleaning up afterwards (for instance each element of the array has at least u' in front of it) and is obviously fragile if any of the elements contain a comma.

Is there a cleaner/easier/better/simpler way of doing this?

Upvotes: 1

Views: 1128

Answers (2)

Jonathan Vanasco
Jonathan Vanasco

Reputation: 15680

Your best bet is to write a Python script that updates the mysql datastore with JSON, which can be easily parsed by just about every language out there. ( as @Hugo Dozois noted ]

Personally, I wouldn't try to read this in PHP. The example you showed has 2 unicode strings in a flat list... but you're likely going to run into more issues and edge cases as time goes on. You might have some unicode strings, other byte strings, some numbers... possibly even nested lists or dicts.

If you didn't inherit it, and were 100% sure of what's going on - then sure, you could parse stuff. But it should take less than 5 minutes to write and run a Python script that converts this to JSON and solves all your problems.

Upvotes: 4

ficuscr
ficuscr

Reputation: 7054

You could use preg_match_all and do this:

$test = "[u'Person 1', u'Person 2']";

preg_match_all('/u\'(.*?)\'/', $test, $matches);

var_dump($matches);

/*
array(2) { 
[0]=> array(2) { 
    [0]=> string(11) "u'Person 1'" 
    [1]=> string(11) "u'Person 2'" } 
[1]=> array(2) { 
    [0]=> string(8) "Person 1" 
    [1]=> string(8) "Person 2" 
    } 
} 
*/

Upvotes: 2

Related Questions