簡體   English   中英

來自php網頁的回顯文本

[英]Echo Text from php Webpage

我在網頁中有一些文本,需要在php頁面中回顯。

如果文字是這樣的

"translatedText":"Ciao mondo"

我用這個PHP代碼

<?php 
$tr=translatedText; 
$Text=file_get_contents("http://mymemory.translated.net/api/get?langpair=en|it&q=Hello%20World!"); 
$regex = "/".$tr."=\"([^\"]+)\"/"; 
preg_match_all($regex,$Text,$Match); 
$fid=$Match[1][0]; 
echo $fid; 
?>

結果不錯

Ciao mondo

但是如果文字是這樣的

{"translatedText":"Ciao mondo"}

我沒有任何結果如何提取

喬蒙多

那里的文字?

使用json_decode

$var = '{"translatedText":"Ciao mondo"}';

var_dump(json_decode($var));

輸出:

object(stdClass)#1 (1) {
  ["translatedText"]=>
  string(10) "Ciao mondo"
}

工作演示

或者沒有stdClass ;

  var_dump(json_decode($var, true));

工作演示

輸出

array(1) {
  ["translatedText"]=>
  string(10) "Ciao mondo"
}

這種結構稱為JSON ,而不僅僅是字符串。

...
$tr = json_decode($Text,TRUE);
echo $tr["translatedText"];
...

您需要驗證字符串是否包含在{..}否則您的JSON無效,因此解碼將失敗。

更新

根據收到的JSON,您應該執行以下操作:

$tr = json_decode($Text,TRUE);
echo $tr["responseData"]["translatedText"];

使用json_decode ,但解碼為數組:

<?php
$response = file_get_contents('http://mymemory.translated.net/api/get?langpair=en|it&q=Hello%20World!');
$array = json_decode($response,1);

echo $array['responseData']['translatedText'];

你也可以:

var_dump($array);

查看整個數組的外觀。

您可以使用json_decode:

$Text = json_decode($Text);
echo $Text['translatedText'];

或假設大括號僅出現在字符串的preg_match_all ,您可以在preg_match_all之前嘗試一下:

echo substr($Text, 1, -1);

使用JSON_DECODE

<?php

$json = '{"foo-bar": 12345}';

$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM