2017-04-11 45 views
-1

http://ufc-data-api.ufc.com/api/v1/us/fighters/title_holders如何以純文本查看此文件以解析數據?

我想從上面的鏈接分析數據,我想查看,因爲我覺得這可能更容易閱讀開始之前純文本顯示的信息?我不知道如何做到這一點,之前我曾做過這樣的事情,但從前不久,所以我正試圖讓自己恢復精力。

任何幫助,將不勝感激。

到目前爲止我的代碼是:

<?php 

    //Calling URL XML 
    $urltitleholders = ("http://ufc-data-api.ufc.com/api/v1/us/fighters/title_holders"); 

    //Loading URL as XML 
    $titleholders_array = simplexml_load_file($urltitleholders); 

    foreach ($titleholders_array as $ufcth) { 

    echo "<pre>"; 
    echo $ufcth; 
    echo "</pre>"; 
} 
+0

這是json ...和解析json更容易..你想從那個文件得到什麼。 –

+0

請問,api響應是json,你如何使用xml_ *庫解析它? – hassan

+0

要以純文本形式查看_JSON_(正如其他人指出的那樣),只需瀏覽到url即可。我也猜測你沒有檢查錯誤日誌或顯示錯誤,因爲這應該會引發一些警告。 –

回答

1
<?php 

$url = "http://ufc-data-api.ufc.com/api/v1/us/fighters/title_holders"; 
$data = file_get_contents($url); 
$users_data = json_decode($data, true); 
$error = json_last_error(); 
$data_to_get = ["wins", "losses", "first_name", "last_name", "weight_class"]; 
if (!$error) { 
    $table = "<table><tr> <th>Name</th> <th>Wins</th> <th>Losses</th> <th>Weight Class</th> </tr>"; 
    foreach ($users_data as $user_data) { 
     $table .= "<tr><td>" . $user_data['first_name'] . " " . $user_data['last_name'] . "</td><td>" . $user_data['wins'] . "</td><td> " . $user_data['losses'] . "</td><td> " . $user_data['weight_class'] . "</td></tr>"; 
    } 
    $table . "</table>"; 
    echo $table; 
} else { 
    echo "Error occured : $error"; 
} 

這裏是你如何從JSON數據,轉換成數組以得到你需要具體的事情。

+0

@MagnusEriksson對不起那個粗心 –

+0

我想這個輸出數據到表中,我創建瞭如下的表頭: '

「;」 這將是正確的代碼,用來舉例 - ? 回聲(」 ​​‘$ users_data->勝’ 等等... – Ryan

+0

@Ryan它只是你如何讓你可以修改。它適合你的需要 –

UFC衛冕冠軍
名稱 損失 重量級別