简体   繁体   English

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

[英]How to display data from json url using php decode?

I am not able to display data from this url using php json decode: https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it 我无法使用php json解码显示来自此URL的数据: https : //api.mymemory.translated.net/get? q = Hello%20World! & langpair = en|it

here is the data provider: https://mymemory.translated.net/doc/spec.php 这是数据提供者: https : //mymemory.translated.net/doc/spec.php

thanks. 谢谢。

What I want is to setup a form to submit words and get translation back from their API. 我想要的是设置一个表单以提交单词并从其API返回翻译。

here is my code sample: 这是我的代码示例:

 <?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 translation echo $data; ?> 

My guess is that you might likely want to write some for loops with if statements to display your data as you wish: 我的猜测是,您可能希望使用if语句编写一些for循环,以if需要显示数据:


Test 测试

$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;

Output 产量

Ciao Mondo!

<?php

$html = '
<!DOCTYPE html>
<html lang="en">
<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;

?>

Output 产量

<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
<p>Ciao Mondo!</p>
</body>

After many researches I got it working this way: 经过大量研究,我发现它是这样工作的:

$json = file_get_contents('https://api.mymemory.translated.net/get?q=Map&langpair=en|it');  
$obj = json_decode($json);   
echo $obj->responseData->translatedText;

thank you all. 谢谢你们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM