2014-01-31 30 views
0

我不能讓下面的陣列更換回車和新行與HTML休息<br />在JSON數組轉換的換行來換行:JSON_decode和nl2br

JSON陣列:

{「水果」 : 「蘋果」, 「素食者」: 「胡蘿蔔\ r \ nCelery \ r \ n \ r \ nCucumbers」}

我想這和有沒有運氣:

$ html = json_decode(nl2br($ json),true);

換行符在HTML本身的源代碼中是可見的,但是我無法獲得<br />代碼來替換'換行符'。

我試過這個建議也並沒有工作,要麼: Replacing \r\n (newline characters) after running json_encode

+0

你是怎麼得到json的?我認爲更好的替換之前,使JSON編碼或之後,如果你沒有編輯JSON的可能性 –

回答

1

運行nl2br()解碼JSON後,不在JSON數組源上。

0

也許你應該嘗試

$arJson = array('fruit' => 'apple', 
       'veggies' => array('carrot', 'celery', 'cucumbers')); 

header('Content-Type: application/json'); 

print json_encode($arJson); 

它返回一個JSON

然後使用jQuery或你最喜歡的庫(甚至是一個定製版本)發送一個ajax請求到頁面。

$.ajax({ 

    url: 'frtsnvgs.php', 
    dataType: 'JSON', 
    success: function(oData) { 
     $.each(oData, function(key, value) { 
      document.write(key + ': ' + value + '<br>'); 
     }); 
    } 

}); 
0

試試看看這個代碼。這可能對你有所幫助

$json = '{"Fruit":"Apple","Veggies":"Carrot\r\nCelery\r\n\r\nCucumbers"}'; 
$json = json_decode($json,true); 
array_walk($json, function(&$val){$val = html_entity_decode(nl2br($val));}); 
echo "<pre>"; 
print_r($json); 
echo "</pre>"; 
exit;