我将如何解析“var coords = {'x':982,'y':1002};”在PHP?

时间:2011-03-01 01:57:45

标签: php

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

通过Curl访问时,API会返回上述代码。

我需要将x和y值解析为变量。这两个值的长度也不总是相同。我不确定最好的办法是什么。

我的想法是使用substr来切断正面和背面,使其为'x' : 982, 'y' : 1002,使用explode来获取带有x' : 982的变量和带有{{'y' : 1002的变量1}},然后再次使用explode获取9821002,最后删除空格。

我不确定这是不是正确的道路。这是正确的做法吗?或者你会采取另一种方式吗?

此外,我使用的API是用于Javascript但我使用PHP,他们没有PHP API。

修改

我有:

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

现在但这似乎不起作用。

5 个答案:

答案 0 :(得分:3)

这很简单,只需使用json_decode功能。

答案 1 :(得分:1)

使用json_decode。这将产生一个对象或一个数组,具体取决于assoc参数。

答案 2 :(得分: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);

这取决于您发布的响应,如果有多行或者字符串中有单引号等,它将无效。

$return上运行json_decode不起作用,因为它不是JSON,它是一个javascript(正如你所说的这个API是用于Javascript的)。

首先,我们删除变量赋值并得到结果:

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

我认为这是有效的JSON,具体取决于您使用它来解码它。在PHP中,这是无效的,因为键/名称必须用双引号括起来,而不是单引号。

所以在单引号和双引号上使用str_replace

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

我们没有PHP的有效JSON。如果你json_decode这将得到一个stdClass对象。并且可以像这样访问值:

$coords = json_decode($json);
echo $coords->x;
echo $coords->y;

答案 3 :(得分:1)

json_decode不起作用,因为虽然该字符串是有效的JavaScript,但它不是有效的JSON。

如果字符串格式与您发布的完全一致,我只需使用preg_match_all

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

原因很简单:虽然可以在没有正则表达式的情况下完成,但是更少的代码等于更少的问题。

答案 4 :(得分:0)

<?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()

更新,你的代码不起作用的原因是你必须使用双引号来覆盖x和y,抱歉我没有彻底阅读你的整个问题,基本上只提供了解析JSON的工具。不知道你有一个javascript声明。我道歉:

<?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'});
?>