Wonder, I get from some API the following string:

parseresponse({"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}});

for some reason I can't replace it to Array when I using:

var_dump(json_decode($content));

and I trying with php function also:

function object2array($object) {
if (is_object($object)) foreach ($object as $key => $value) $array[$key] = $value;
    else $array = $object;
return $array;
}

any idea?..

share|improve this question

2 Answers

You're trying to parse JSONP response as JSON, you should remove wrapping function first.

$response = 'parseresponse({"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}});';
$json = preg_replace('/^parseresponse\((.*)\);/', '$1', $response);
$data = json_decode($json, true);
print_r($data);
share|improve this answer
empty result... WEIRD! :( – Hanan Feb 5 '12 at 8:48
That's strange, if your input matching the sample you provided it output should be correct. If not just tune regex for your needs. – Juicy Scripter Feb 5 '12 at 9:46

You could try something like this:

$content = '{"eurusd":{ "id": "eurusd", "category": "Forex", "price": 1.3161, "name": "EUR/USD", "buy": 1.3162, "sell": 1.3159, "change": 0.00, "date":1328288216000}}';

function toArray($data) {
    if (is_object($data)) $data = get_object_vars($data);
    return is_array($data) ? array_map(__FUNCTION__, $data) : $data;
    }

$newData = toArray (json_decode($content));

print_r($newData);

output will be:

Array ( [eurusd] => Array ( [id] => eurusd [category] => Forex [price] => 1.3161 [name] => EUR/USD [buy] => 1.3162 [sell] => 1.3159 [change] => 0 [date] => 1328288216000 )

)

share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.