为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用php解码显示来自json url的数据?

如何使用php解码显示来自json url的数据?

PHP
手掌心 2021-11-19 15:18:20
我无法使用 php json 解码显示来自这个 url 的数据:https : //api.mymemory.translated.net/get? q = Hello%20World! & langpair = en|it这是数据提供者:https : //mymemory.translated.net/doc/spec.php谢谢。我想要的是设置一个表单来提交单词并从他们的 API 中获取翻译。这是我的代码示例:<?php$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');// parse the JSON$data = json_decode($json);// show the translationecho $data;?>
查看完整描述

2 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

我的猜测是,您可能希望编写一些带有if语句的for 循环来根据需要显示数据:


测试

$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');

$data = json_decode($json, true);


if (isset($data["responseData"])) {


    foreach ($data["responseData"] as $key => $value) {

        // This if is to only display the translatedText value //

        if ($key == 'translatedText' && !is_null($value)) {

            $html = $value;

        } else {

            continue;

        }

    }

} else {

    echo "Something is not right!";

}


echo $html;

输出

Ciao Mondo!

<?php


$html = '

<!DOCTYPE html>

<html>

<head>

<title>read JSON from URL</title>

</head>

<body>

';


$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');

$data = json_decode($json, true);


foreach ($data["responseData"] as $key => $value) {

    // This if is to only display the translatedText value //

    if ($key == 'translatedText' && !is_null($value)) {

        $html .= '<p>' . $value . '</p>';

    } else {

        continue;

    }

}


$html .= '

</body>

</html>';


echo $html;


?>

输出

<!DOCTYPE html>

<html>

<head>

<title>read JSON from URL</title>

</head>

<body>

<p>Ciao Mondo!</p>

</body>


查看完整回答
反对 回复 2021-11-19
?
陪伴而非守候

TA贡献1757条经验 获得超8个赞

经过多次研究,我以这种方式工作:


$json = file_get_contents('https://api.mymemory.translated.net/get?q=Map&langpair=en|it');  

$obj = json_decode($json);   

echo $obj->responseData->translatedText;

谢谢你们。


查看完整回答
反对 回复 2021-11-19
  • 2 回答
  • 0 关注
  • 134 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信