使用echo值生成JSON输出

时间:2013-04-28 07:04:28

标签: php json

我有一个功能

function currency($from_Currency,$to_Currency,$amount) {

成功回显结果。

echo currency("USD","INR",1.00),"india.png","\n";
echo currency("USD","EUR",1.00),"europe.png","\n";
echo currency("USD","GBP",1.00),"england.png","\n";
echo currency("USD","AED",1.00),"uae.png","\n";
echo currency("USD","CNY",1.00),"china.png","\n";
echo currency("USD","CAD",1.00),"canada.png","\n";
echo currency("USD","PKR",1.00),"pakistan.png","\n";
echo currency("USD","ZAR",1.00),"southafrica.png","\n";
echo currency("USD","CAD",1.00),"canada.png","\n";
echo currency("USD","JPY",1.00),"japan.png","\n";
echo currency("USD","NZD",1.00),"newzealand.png","\n";
echo currency("USD","NPR",1.00),"nepal.png","\n";

由于只有在函数中传递USD,INR,EUR ...值时才能返回回波值。我也附加了图像名称。 我想用echo值生成JSON输出。有人可以提供我的想法。

我从echo值得到的输出就像这样

54.42india.png
0.77europe.png
0.65england.png
3.67uae.png
6.17china.png
1.02canada.png
98.48pakistan.png
9.1southafrica.png
1.02canada.png
98.22japan.png
1.18newzealand.png
87.01nepal.png

提前致谢

2 个答案:

答案 0 :(得分:3)

据我所知,您的问题最好将代码重新分解如下。

  • 创建一个包含所需数据的数组。
  • 然后使用json_enocde对数据进行编码 - 它返回值
  • 的JSON表示

EG:

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);

O / P

{"a":1,"b":2,"c":3,"d":4,"e":5}

然后使用json_decode解码相关数据。

注意

您不必使用echos创建JSON对象。使用上述方法对您来说会容易得多。使用jsonlint验证您的JSON对象。

答案 1 :(得分:1)

可能是创建标准类对象并将其转换为json的最简单方法。

$list = array();

$currency = new stdClass();
$currency->currency = currency("USD","INR",1.00);
$currency->image = "india.png";

$list[] = $currency;


echo json_encode($list);

如果您只想输出对象

echo json_encode($currency);