How would I parse "var coords = {'x': 982, 'y': 1002};" in php?

var coords = {'x' : 982, 'y' : 1002 };

The above code is returned by the API when accessed via Curl.

I need to analyze the values ​​of x and y in variables. These two values ​​are also not always the same. I'm not sure the best way to do this.

My idea was to use substrto cut the front and back pieces to 'x' : 982, 'y' : 1002use explodeto get var c ' x' : 982and the other with 'y' : 1002, and then use explodeagain to receive 982and 1002, and, finally, remove the spaces.

I am not sure if this is the right way or not. Is this the right way to do this, or will you do it differently?

Also, the API I use is for Javascript, but I use 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 it does not work.

+3
source share
5 answers

json_decode will not work, because although the string is valid JavaScript, it is invalid JSON.

If the string format is exactly the same as you posted, I would simply use preg_match_all:

preg_match_all('/([0-9]+)/', $input, $matches);
list($x, $y) = $matches[0];

The reason is simple: although this can be done without regular expression, less code and less problems.

+1
source

It's simple, just use json_decode .

+3
source

json_decode. assoc.

+1

, :

<?php
$return = "var coords = {'x' : 982, 'y' : 1002 };";
$json = str_replace("'", '"', substr($return, strlen('var coords = '), -1));
$coords = json_decode($json);
var_dump($coords);

, , , , ..

json_decode $return , JSON, javascript ( , API Javascript).

, :

{'x' : 982, 'y' : 1002 }

, JSON , . PHP , / , .

, str_replace

{"x" : 982, "y" : 1002 }

, JSON PHP. json_decode, stdClass. :

$coords = json_decode($json);
echo $coords->x;
echo $coords->y;
+1
<?php
$json= '{"x" : 982, "y" : 1002 }';
$obj = json_decode($json);
print($obj->{'x'}); //this will give you 982
print($obj->{'y'}); //this will give you 1002
?>

json_decode()

UPDATED, the reason your code didn't work is because you should use a double quote to cover x and y, sorry, I did not read your whole question persistently and basically provided you with just a JSON parsing tool. Didn't know that you have a javascript expression. I apologize:

<?php
$result = "var coords = {'x' : 982, 'y' : 1002 };";
$result = substr($result, 13);
$result = substr($result, 0,strlen ($result) - 1);
$result = preg_replace("/'/", '"', $result);
$json_obj = json_decode($result);
$x_coord = $json_obj->{'x'};
$Y_coord = $json_obj->{'y'};
print('x coord: ' . $json_obj->{'x'}.PHP_EOL);
print('y coord: ' . $json_obj->{'y'});
?>
0
source

Source: https://habr.com/ru/post/1795382/


All Articles