如何使用PHP代码以json格式输出

时间:2016-06-03 10:56:12

标签: php json

我已经编写了获取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格式输出这个输出。什么代码必须改变请帮帮我

2 个答案:

答案 0 :(得分:0)

你应该在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);  // <<<<<<<<<<<
    }
   ?>

答案 1 :(得分:0)

试试这个

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

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