简体   繁体   English

来自php网页的回显文本

[英]Echo Text from php Webpage

I have some Text in a web page that i need to echo in my php page'. 我在网页中有一些文本,需要在php页面中回显。

If the text is like this 如果文字是这样的

"translatedText":"Ciao mondo"

I use this php code 我用这个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; 
?>

The result it good 结果不错

Ciao mondo

But if the text is like This 但是如果文字是这样的

{"translatedText":"Ciao mondo"}

I don't have any result How to extract the 我没有任何结果如何提取

Ciao mondo 乔蒙多

text from there? 那里的文字?

Use json_decode 使用json_decode

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

var_dump(json_decode($var));

Output: 输出:

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

WORKING DEMO 工作演示

OR without stdClass ; 或者没有stdClass ;

  var_dump(json_decode($var, true));

WORKING DEMO 工作演示

output 输出

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

This kind of structure is named JSON and is not just about strings. 这种结构称为JSON ,而不仅仅是字符串。

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

You need to verify that the string is enclosed on {..} otherwise your JSON would not been valid, thus decoding will fail. 您需要验证字符串是否包含在{..}否则您的JSON无效,因此解码将失败。

UPDATE 更新

Based on the JSON you receive, you should do this: 根据收到的JSON,您应该执行以下操作:

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

Use json_decode , but decode to array: 使用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'];

You can also: 你也可以:

var_dump($array);

To see how this whole array looks like. 查看整个数组的外观。

You can use json_decode: 您可以使用json_decode:

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

or assuming the curly brackets occur only as first and last characters of your string, you can try this before your preg_match_all : 或假设大括号仅出现在字符串的preg_match_all ,您可以在preg_match_all之前尝试一下:

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

Use JSON_DECODE 使用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