How would I parse "var coords = {'x' : 982, 'y' : 1002 };" in php? -
var coords = {'x' : 982, 'y' : 1002 }; the above code returned api when access via curl.
i need parse x , y values variables. 2 values not same length. i'm not sure best way is.
my idea use substr cut off front , it's 'x' : 982, 'y' : 1002, use explode var 'x' : 982 , 'y' : 1002, use explode again 982 , 1002, , remove spaces.
i'm unsure if right path or not. right way or way?
also, api using meant javascript using php, don't have 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 doesn't seem work.
json_decode won't work because although string valid javascript, not valid json.
if string format posted, i'd use preg_match_all:
preg_match_all('/([0-9]+)/', $input, $matches); list($x, $y) = $matches[0]; the reason simple: while done without regex, less code equals less problems.
Comments
Post a Comment