【问题标题】:how to get output in json format using php code如何使用 php 代码获取 json 格式的输出
【发布时间】:2016-06-03 10:56:12
【问题描述】:

我已经编写了获取 Web 服务的 php 代码 我的想法是,如果我给书名,Web 服务应该返回我编写的代码的书价

service.php

 <?php 

 include 'lib/nusoap.php';   //load the library file
 include 'lib/fun.php';
 $server=new nusoap_server(); //create instance to the class
 $server->configureWSDL("demo","urn:demo");  //it will accept the two     parameters one name of the webservice,two namespace of the web service
   $server->register(
    "price",  //name of function
              array("name"=>'xsd:string'), //inputs
              array("return"=>"xsd:integer")  //outputs
    );
   $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA :'';
   $server->service($HTTP_RAW_POST_DATA);
 ?>

client.php

 <?php
   require 'lib/nusoap.php'; 

       $client=new nusoap_client("http://localhost/demo/service.php?wsdl");
     $book_name ="abc";
   $price = $client->call('price',array("name"=>"$book_name"));
   if(empty($price))
  echo "book data not available";
 else
    echo $price;

    ?>

fun.php

  <?php 

  function price($name){
   $details=array(

           'abc'=>100,
           'xyz'=>200 
          );
   foreach($details as $n=>$p)
    {
    if($name==$n)
        $price=$p;

    }
    return $price;
    echo json_encode($price);
    }
   ?>

当我运行这段代码时它工作正常,如果我在 soaclient 上检查这个,当我给出书名时

 name: abc 
 it returning the value :100

当我给出书名时,我需要这个 json 格式的输出。需要更改哪些代码,请帮助我

【问题讨论】:

  • return 结束当前方法/函数,因此您的 echo 永远不会运行。它也永远不会做超过一次循环的迭代。

标签: php json


【解决方案1】:

试试这个

 return json_encode(["price"=>$price]);

访问输出:https://eval.in/582574

【讨论】:

    【解决方案2】:

    你应该在 fun.php 中修改:

    <?php 
    
      function price($name){
       $price = array();
       $details=array(
    
               'abc'=>100,
               'xyz'=>200 
              );
       foreach($details as $n=>$p)
        {
        if($name==$n)
            $price[$n]=$p;
    
        }
        return json_encode($price);  // <<<<<<<<<<<
        }
       ?>
    

    【讨论】:

    • 检查这个eval.in/582574,输出将是100,你期望这个代码的json形式是什么?
    猜你喜欢
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2016-03-30
    • 1970-01-01
    • 2017-06-07
    • 2017-08-20
    相关资源
    最近更新 更多