自定义php api与json_encode& json_decode没有返回json字符串

时间:2012-03-21 16:53:06

标签: php json

我最近编写了一个自定义API,用于将数据从不同服务器上的多个网站插入我的数据库......但它有一些问题,我不知道它可能是什么......

以下是我的API代码的摘录示例..

if (function_exists($_GET['method'])) {
        // function exists, so lets run it.
        $_GET['method']();
    } else {
        // function does not exist so lets throw an error.
        $data['respCode'] = "100";
        $data['respMsg'] = "The method you have called does not exist.  Please reformat your call.";
        echo json_encode($data); 
    }

// methods

function newProspect() {
    // lets first check for the lead in the database..

    $sql = mysql_query("SELECT * FROM leads WHERE email = '".$_POST['email']."' LIMIT 1");
    if (mysql_num_rows($sql) >= 1) {
        // duplicate found, so lets just send the data..
        $data = mysql_fetch_assoc($sql);
        $data['respCode'] = "200";
        $data['respMsg'] = "Duplicate Lead.  Information echoed.";
        echo json_encode($data);
    } else {
        // no duplicate found, so lets insert the data..
        $sql = "INSERT INTO leads SET ";
        foreach ($_POST as $key => $value) {
            $sql .= $key." = '".$value."',";
        }
        $sql .= "register_date = '".$rdate."'"; 
        $sql = mysql_query($sql);
        if (!$sql) {
            // could not insert the info into the database so lets throw an error.
            $data['respCode'] = "102";
            $data['respMsg'] = "Could not intert into database.";
            $data['errorMsg'] = mysql_error();

            echo json_encode($data); return json_encode($data);
        } else {
            // lead was inserted into the database just fine, so lets pass back the data.
            $id = mysql_insert_id($sql);
            $sql = mysql_query("SELECT * FROM leads WHERE `idleads` =".$id."");
            $data = mysql_fetch_assoc($id);
            $data['respCode'] = '200';
            $data['respMsg'] = "Lead Entered into Database Successfully.";

            echo json_encode($data);
        }
    }
}

我还创建了一个远程与API通信的类......这可能是问题所在..

<?php

class theApi {
public $apIdomain = 'http://www.domain.com/api/index.php'; // ie: https://www.mydomain.com/admin/

public $APData = array();
public $postUrl = '';

public function __construct() {

}

function method ($meth = 'newProspect') {
    $this->postUrl = $this->apIdomain."?method=".$meth;
    return $this;
}

function postData($pdata) {
    foreach ($pdata as $key => $val) {
        if ($key != 'submit') {
            $this->APData[$key] = $val;
        }
    }
    return $this;
}

function process() {
    $this->APData['ipaddress'] = ip2long($_SERVER['REMOTE_ADDR']);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $this->postUrl);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $this->APData);   
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,0); 
    curl_setopt($ch, CURLOPT_TIMEOUT,30);

    $rawresponse = curl_exec($ch);

    curl_close($ch);

    return $rawresponse;

}
}

$ap = new theApi();

然后我有我的提交者应用程序只是为了测试它...

<?php
$_method = $_GET['method'];
require_once("api.php");
switch ($_method) {

    case 'newProspect':
        $data['name'] = "TestB";
    $data['phone'] = "555-555-5555";
    $data['email'] = "testB@testerdomain1.com";

    $d = $ap->method('newProspect')->postData($data)->process();
break;

case 'updateProspect':

break;

case 'saveProject':
break;

case 'finishApplication':
break;
}

当我通过转到http://www.differentdomain.com/api-test/index.php?method=newProspect运行代码时,我会进入浏览器输出:{"idleads":"1886","classid":"1","ipaddress":"-949980134","register_date":"0000-00-00 00:00:00","name":"TestB","first_name":null,"last_name":null,"phone":"555-555-5555","phone2":null,"email":"testB@testerdomain1.com","age":null,"zip":null,"traffic_source":"1","affiliateid":null,"sversion":null,"purpose":null,"amount":null,"description":null,"respCode":"200","respMsg":"Duplicate Lead. Information echoed."}

所以API本身正在运行......但是我无法在任何地方运行json_decode,而且几乎看起来好像CURL没有从API获取数据......对此的任何帮助都非常感谢。我不知道从哪里开始工作......

感谢。

更改为CURL的新输出:

object(stdClass)#2 (20) { ["idleads"]=> string(4) "1886" ["classid"]=> string(1) "1" ["ipaddress"]=> string(10) "-949980134" ["register_date"]=> string(19) "0000-00-00 00:00:00" ["name"]=> string(5) "TestB" ["first_name"]=> NULL ["last_name"]=> NULL ["phone"]=> string(12) "555-555-5555" ["phone2"]=> NULL ["email"]=> string(33) "justinblacktest@testerdomain1.com" ["age"]=> NULL ["zip"]=> NULL ["traffic_source"]=> string(1) "1" ["affiliateid"]=> NULL ["sversion"]=> NULL ["purpose"]=> NULL ["amount"]=> NULL ["description"]=> NULL ["respCode"]=> string(3) "200" ["respMsg"]=> string(36) "Duplicate Lead. Information echoed." }

1 个答案:

答案 0 :(得分:2)

CURL_RETURNTRANSFER设置为1以返回HTTP请求输出,而不是将其回显到屏幕。

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->postUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->APData);   
// Set to 1
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
curl_setopt($ch, CURLOPT_TIMEOUT,30);

// now $rawresponse actually contains the JSON retrieved
// from the API call.
$rawresponse = curl_exec($ch);

提到in the curl_exec() documentation.