2009-05-24 83 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