2009-05-24 36 views
1

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

这是我到目前为止的代码,它将重新编码数据,因为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。

回答

2

由于VolkerK说,你以前都]}剥逗号:

// ... 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(我认为是你正在尝试做的)是行不通的。

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

3

虽然json_decode()能够解码

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

编辑:json.org链接到Comparison of php json libraries。根据它们的比较图表,例如zend json应该能够解析firefox'bookmark.json。还没有测试过它。

edit2:为什么不简单地测试....? 是,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);

打印
array(7) { 
    ["title"]=> 
    string(0) "" 
    ["id"]=> 
... 
     ["children"]=> 
     array(0) { 
     } 
    } 
    } 
}

+0

那么这有可能吗? – 2009-05-24 20:52:45

+0

我试图避免使用库,但如果这确实结束是唯一的选择,我会研究它。 – 2009-05-24 22:15:46