2014-03-02 46 views
0

我從一個URL使用file_get_contents()獲取這些數據。PHP的正則表達式字符串到列表

[ 
{ 
    "abbr": "bigrapids", 
    "name": "Big Rapids", 
    "lat": 43.68757, 
    "lon": -85.48229, 
    "analytics": "UA-18102548-30" 
}, 
{ 
    "abbr": "bloomington", 
    "name": "Bloomington Transit", 
    "lat": 39.1654, 
    "lon": -86.52643, 
    "analytics": "UA-18102548-24" 
}, 

我需要將每個名稱(Big Rapids,Bloomington Transit)轉換爲無序列表,然後顯示列表。我一直在研究正則表達式fucnctions,我似乎無法弄清楚。任何幫助,將不勝感激。

+4

這是JSON,你不應該需要一個正則表達式。用'json_decode()'解析它。 – nickb

回答

0

它看起來像一個JSON string的開始。假設你有字符串的其餘部分,則可以使用json_decode()解析它:

$data = '...'; 
$parsed = json_decode($data); 
echo '<pre>', print_r($parsed, true), '</pre>'; 
0

live demo

需要decode_json()用於解碼JSON數據,然後你可以有子陣排列,那麼你將擁有所有的名字。

嘗試這樣的:

$json = <<<JSON 
[ 
{ 
    "abbr": "bigrapids", 
    "name": "Big Rapids", 
    "lat": 43.68757, 
    "lon": -85.48229, 
    "analytics": "UA-18102548-30" 
}, 
{ 
    "abbr": "bloomington", 
    "name": "Bloomington Transit", 
    "lat": 39.1654, 
    "lon": -86.52643, 
    "analytics": "UA-18102548-24" 
}] 
JSON; 

$json_d=json_decode($json,true); 
foreach($json_d as $arr){ 
echo $arr['name']." "; 
} 
0
<?php 

$json = <<<EOD 
[ 
{ 
    "abbr": "bigrapids", 
    "name": "Big Rapids", 
    "lat": 43.68757, 
    "lon": -85.48229, 
    "analytics": "UA-18102548-30" 
}, 
{ 
    "abbr": "bloomington", 
    "name": "Bloomington Transit", 
    "lat": 39.1654, 
    "lon": -86.52643, 
    "analytics": "UA-18102548-24" 
}] 
EOD; 

$array = json_decode($json, true); //make sure second parameter is true for a multidimensional array. 

echo '<ul>'; // start ul tag 
foreach($array as $value){ 
    echo '<li>' . $value['name'] . '</li>'; // for each value in array make a list item for it 
} 
echo '</ul>'; // close to ul list tag