【问题标题】:returning JSON in php在 php 中返回 JSON
【发布时间】:2013-10-10 18:26:09
【问题描述】:

谁能告诉我如何从 REST webservice 获取 json。

我的代码如下

在这里当我们运行应用程序时,如果给出例子

localhost/examples/Example.php?method=addInts&n1=3&n2=5

会给我们输出

{"Result":"3 + 5 = 8"}

我们怎么能期望像json一样返回输出

[{"Result":8}]

我的php代码

<?php

  require_once "../Rest.php";

  class Hello
  {
     // example: http://path/to/examples/Example.php?method=sayHello&name=World
     public static function sayHello($name)
     {
        return array("Response" => "Hello, " . $name);
     }

     // example: http://path/to/examples/Example.php?method=addInts&n1=3&n2=5
     public static function addInts($n1, $n2)
     {
        if (is_numeric($n1) && is_numeric($n2))
        {
          return array("Result" => "$n1 + $n2 = " . (string)($n1 + $n2));
        }
        else
        {
          return array("Error" => "Parameters must be numeric.");
        }
     }
  }

  $rest = new Server(Hello);
  $rest->handle();

?>

【问题讨论】:

    标签: php json web-services rest


    【解决方案1】:

    不确定 REST,但通常的 json_encode() 不起作用吗?

    // example: http://path/to/examples/StaticExample.php?method=sayHello&name=World
    public static function sayHello($name)
    {
    
        $myArray = array("Response" => "Hello, " . $name);
        return json_encode($myArray);
    }
    

    【讨论】:

    • json_encode 会起作用,但是,如果您有一个多维数组,PHP 只会在响应周围加上方括号。否则它只会使用大括号,我的 ajax 应用程序看起来很好。旁注,我从未见过以我想要的方式返回工作,在这些情况下,我总是不得不使用 echo 来调用我的 ajax 来获取它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 2012-12-18
    • 1970-01-01
    • 2013-05-18
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多