【发布时间】:2021-02-20 17:54:57
【问题描述】:
您好,我在显示通过请求获取到外部 api 休息的 json 数据时遇到问题。我正在使用 wordpress 发出请求,并且返回的 json 文件没有错误,所以一切正常。当我尝试在 html 表中插入数据时,没有显示任何内容。下面我插入我正在使用的返回的 json 和 php 代码。
JSON
object(stdClass)#5501 (2) { ["success"]=> bool(true) ["data"]=> array(12) { [0]=> object(stdClass)#5562 (7) { ["sport_key"]=> string(26) "soccer_turkey_super_league" ["sport_nice"]=> string(19) "Turkey Super League" ["teams"]=> array(2) { [0]=> string(11) "Denizlispor" [1]=> string(16) "Yeni Malatyaspor" } ["commence_time"]=> int(1604831497) ["home_team"]=> string(16) "Yeni Malatyaspor" ["sites"]=> array(4) { [0]=> object(stdClass)#5641 (4) { ["site_key"]=> string(10) "paddypower" ["site_nice"]=> string(11) "Paddy Power" ["last_update"]=> int(1604835079) ["odds"]=> object(stdClass)#5643 (1) { ["h2h"]=> array(3) { [0]=> float(31) [1]=> float(1.06) [2]=> float(10) } } } [1]=> object(stdClass)#5647 (4) { ["site_key"]=> string(7) "betfair" ["site_nice"]=> string(7) "Betfair" ["last_update"]=> int(1604835077) ["odds"]=> object(stdClass)#5648 (2) { ["h2h"]=> array(3) { [0]=> float(26) [1]=> float(1.12) [2]=> float(10.5) } ["h2h_lay"]=> array(3) { [0]=> float(55) [1]=> float(1.13) [2]=> float(13) } } } ......``
PHP 脚本
add_shortcode( 'external_data', 'callback_function_name' );
function callback_function_name(){
$url = 'https://xxxxxxxxxx&apiKey=xxxxxxxxx';
$arguments = array(
'method' => 'GET',
);
$response = wp_remote_get($url, $arguments);
if ( is_wp_error($response)) {
$error_message = $response->get_error_message();
return "Something went wrong: $error_message";
}
$results = json_decode( wp_remote_retrieve_body( $response ));
//var_dump($results);
$html .='';
$html .= '<table>';
$html .='<tr>';
$html .='<td>Exemple<td>';
$html .='<td>Exemple<td>';
$html .='<td>Exemple<td>';
$html .='<td>Exemple<td>';
$html .='<td>Exemple<td>';
$html .='</tr>';
foreach( $results as $result ){
$html .='<tr>';
$html .='<td>' . $result->data . '<td>';
$html .='<td>' . $result->sport_key . '<td>';
$html .='<td>' . $result->sport_nice . '<td>';
$html .='<td>' . $result->teams . '<td>';
$html .='<td>' . $result->commence_time . '<td>';
$html .='</tr>';
}
$html .='</table>';
return $html;
}
?>
【问题讨论】:
-
欢迎使用 stackoverflow ...您的安装是特定于您的。最后尝试
var_dump($html);,看看你生成的html代码是否正常,然后更新你的问题。 -
嗨,不,你的解决方案不起作用......
标签: php json api parsing wordpress-rest-api