0

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?..

2 Answers 2

2

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

1 Comment

That's strange, if your input matching the sample you provided it output should be correct. If not just tune regex for your needs.
0

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 )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.