1

是否可以使用 PHP 输出特定的 JSON 数据(从 Firefox 书签中导出)。

这是我到目前为止的代码,它将重新编码数据,因为 Firefox 没有以正确的 UTF-8 方式导出它。我还从文件末尾删除了结尾的 , 。

<?php
// Read the file blah blah
$hFile = "../uploads/james.json";
$hFile = file_get_contents($hFile);
$hFile = utf8_encode($hFile);
// Remove the trailing comma because Firefox is lazy!!!!
$hFile = substr($hFile, 0, strlen($hFile)-3) . "]}";

$hDec = json_decode(fixEncoding($hFile));

foreach($hDec['uri'] as $hURI) {
    // Output here
}

// Fixes the encoding to UTF-8
function fixEncoding($in_str) {
    $cur_encoding = mb_detect_encoding($in_str);
    if($cur_encoding == "UTF-8" && mb_check_encoding($in_str,"UTF-8")){
        return $in_str;
    }else{
        return utf8_encode($in_str);
    }
}
?>

使用 var_dump,除了整个数据之外,我无法获得任何输出。

4

2 回答 2

3

虽然 json_decode() 能够解码

<?php
$c = '{"title":""}';
$bookmarks = json_decode($c);
var_dump($bookmarks);
它失败了
$c = '{"title":"",}';
最后的“空”元素会关闭解析器。这正是我的bookmarks.json 的样子
{"title":"", ... "children":[]},]}

编辑:json.org链接到php json 库的比较。根据他们的比较图,例如zend json应该能够解析firefox的bookmark.json。虽然没有测试过。

编辑2:为什么不简单地测试一下......?是的,zend json 能够解析未修改的 bookmarks.json

require 'Zend/Json.php';

$encodedValue = file_get_contents('Bookmarks 2009-05-24.json'); $phpNative = Zend_Json::decode($encodedValue); var_dump($phpNative);

印刷
数组(7){
  [“标题”]=>
  字符串(0)“”
  [“身份证”]=>
...
      [“孩子”]=>
      数组(0){
      }
    }
  }
}

于 2009-05-24T20:36:26.400 回答
2

正如 VolkerK 所说,您必须在] and }之前去掉逗号:

// ... row 7
// Remove the trailing comma because Firefox is lazy
$hFile = preg_replace('/,\s*([\]}])/m', '$1', $hFile);

// ... or using str_replace
$hFile = str_replace(',]', ']', str_replace(',}', '}', $hFile));

但是,您尝试访问书签的 URI 的方式(我认为这是您正在尝试做的)将不起作用。

重新检查文件的格式/架构。

于 2009-05-24T20:58:25.543 回答