var coords = {'x' : 982, 'y' : 1002 };
The above code is returned by the API when access via Curl.
I need to parse the x and y values into variables. The two values are also not always the same length. I’m not sure what the best way to do this is.
My idea was to use substr to cut off the front and back so it’s 'x' : 982, 'y' : 1002, use explode to get a var with ‘x' : 982 and another with 'y' : 1002, then use explode again to get 982 and 1002, and finally remove the spaces.
I’m unsure if this is the right path or not. Is this the right way to do it or would you do this another way?
Also, the API I am using is meant for Javascript but I am using PHP, they don’t have a PHP
API.
Edit:
I have:
<?php
$result = "var coords = {'x' : 982, 'y' : 1002 };";
$result = substr($result, 13);
$result = substr($result, 0,strlen ($result) - 1);
$json_obj = json_decode($result);
$x_coord = $json_obj->{'x'};
$Y_coord = $json_obj->{'y'};
echo 'x:' . $x_coord;
echo '<br>';
echo 'y:' . $y_coord;
?>
now but that doesn’t seem to work.
json_decodewon’t work because although the string is valid JavaScript, it is not valid JSON.If the string format is exactly as you posted, I’d simply use
preg_match_all:The reason is simple: while it could be done without regex, less code equals less problems.