我在这里研究了如何解码字符串,但它要求密钥用引号括起来,而我的数据没有,例如:
以下数据保存在.txt文件中,我使用file_get_contents()
读取文件,我无法控制以下数据。
这是我的数据
"{
ip : "192.168.1.110",
startFrame : "1",
endFrame : "11",
startedCurrentFrameAt: "1397529891",
status: "rendering",
currentFrame: "0"
}"
在php中,我希望能够读取这些数据,并访问每个密钥,这就是我尝试过的:
$arr = json_decode($data, true)['status'];
$arr只是返回null,因为密钥没有被引用,有解决办法吗?
我已经找到了很多这个问题的答案,但都引用了密钥。
试试这个
<?php
function fix_json($s) {
$s = preg_replace('/('w+):/i', '"'1":', $s);
return $s;
}
$data = '{
ip: "192.168.1.110",
startFrame: "1",
endFrame: "11",
startedCurrentFrameAt: "1397529891",
status: "rendering",
currentFrame: "0"
}';
$valid_json = fix_json($data);
$arr = json_decode($valid_json , true);
$status = $arr['status'];
echo $status;
演示
为此使用preg_replace_callback()
代码中发生了什么
首先,正则表达式试图查找空间和:
之间的条目,然后将它们周围的引号连接起来。最后,str_replace()
充当包装器来修复JSON大括号。
<?php
$json='"{
ip : "192.168.1.110",
startFrame : "1",
endFrame : "11",
startedCurrentFrameAt: "1397529891",
status: "rendering",
currentFrame: "0"
}"';
function cb_quote($v)
{
return '"'.trim($v[1]).'":';
}
$newJSON=str_replace(array('"{','}"'),array('[{','}]'),preg_replace_callback("~ (.*?):~","cb_quote", $json));
echo $arr = json_decode($newJSON, true)[0]['status'];
OUTPUT :
rendering
工作演示
通过文件。。(编辑)
<?php
$json = trim(file_get_contents('new.txt'));
//Modifications..
$json = str_replace(array('{','}',':',','),array('[{" ',' }]','":',',"'),$json);
function cb_quote($v)
{
return '"'.trim($v[1]).'"';
}
$newJSON=preg_replace_callback("~'"(.*?)'"~","cb_quote", $json);
echo $arr = json_decode($newJSON, true)[0]['status']; //"prints" rendering
我会使用PHP爆炸函数来实现这一点。Explode类似于javascript的.split函数,它将获取一个字符串并将其分解为一个可用数据数组。
所以,像这样的东西应该可以工作,但你需要先删除末尾的"{和}":
// lets assume that your data is $mydata, for brevity's sake.
$mydata_arr = new Array();
$item_arr = new Array();
$newdata_arr = new Array();
$mydata_arr = explode(',',$mydata); // explode where there is a comma
foreach($item in $mydata_arr){
$item_arr = explode(':',$item); // explode where there is a colon
// this gives us keys and values in a the $item_arr at [0] and [1]
$key = $item_arr[0];
$value = $item_arr[1];
// reassign these in a new, usable array
$newdata_arr[$key] = $value;
}
现在,我知道这是粗鲁和不雅的,但我想用一种能帮助你了解需要用英语做什么的方式来解释。我希望它能有所帮助。