通过python将JSON发送到外部PHP监听器

时间:2015-01-06 10:05:39

标签: php python json

我遇到的问题有点奇怪,但我会尽力解释。

目前,我运行了一系列脚本,这些脚本生成一个JSON文件,用于存储有关服务器机房的详细信息。然后将此JSON文件传递给PHP侦听器,该侦听器通过解析JSON并提取信息来填充数据库。

当使用mozilla add on" Poster"时,JSON会向数据库发帖。但是无论何时我从我的VM运行它并尝试自动化它我都会收到此错误 -

致命错误:只能通过引用传递变量

我也得到了一堆这些错误

非法字符串偏移'首字母缩略词'在 C:\ xampp \ htdocs \ globalHEC \ php_http_request \ hecdashboard.php 98

发送python方法:

def send_json_results(result_dict, server_ip, server_port):
'''Send the json file usinf http to the listening monitoring server'''
    url="http://%s:%s/globalHEC/php_http_request/hecdashboard.php?id=ni100&type=json" %(server_ip, server_port)
    data=json.dumps(result_dict)
    req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
    f = urllib2.urlopen(req)
    resp = f.read()
    print "Results sent to %s with response: %s" % (server_ip, resp)

PHP侦听器代码段:

$locres = $mysqli->query("SELECT loc1.Id FROM `location` AS loc1 WHERE loc1.Timestamp = (SELECT MAX(loc2.Timestamp) FROM location AS loc2 WHERE loc2.Id = loc1.Id LIMIT 1) AND
                    loc1.Id = '".$jsonArray_new["acronym"]."' AND 
                    loc1.Continent= '".$jsonArray_new["continent"]."' AND 
                    loc1.Country = '".$jsonArray_new["country"]."' AND
                    loc1.City = '".$jsonArray_new["city"]."' AND
                    loc1.Latitude = '".$jsonArray_new["latitude"]."' AND
                    loc1.Longitude = '".$jsonArray_new["longitude"]."' AND
                    loc1.CellVersion = '".$jsonArray_new["cell_version"]."' AND
                    loc1.NumberOfCells = '".$jsonArray_new["number_of_cells"]."' LIMIT 1;");

//any changes or fresh Location, so add it 
if ($locres->num_rows == 0) { 
if ($stmt = $mysqli->prepare('INSERT INTO location (Id, Continent, Country, City, Latitude, Longitude, CellVersion, NumberOfCells, Timestamp) VALUES (?,?,?,?,?,?,?,?,?)')) {
$res = $stmt->bind_param("ssssddsis", $jsonArray_new['acronym'], $jsonArray_new['continent'], $jsonArray_new['country'], $jsonArray_new['city'], $jsonArray_new['latitude'], $jsonArray_new['longitude'], $jsonArray_new['cell_version'], $jsonArray_new['number_of_cells'], $jsonArray_new['timestamp']);
        $finishings += (int)$stmt->execute();
        $finishingQuota++;
        }
}

jsonArray_new初始化如下:

$file_content = file_get_contents('php://input');
echo "try to create file: ".$folder.$location.".json";
$numbytes = file_put_contents($folder.$location.".json", $file_content) OR EXIT("ERROR: Creation of ".$location.".json was not possible.");
print "$numbytes bytes written\n";
//} 
$jsonString_new = $file_content;

$jsonArray_new = json_decode($jsonString_new, true); 

1 个答案:

答案 0 :(得分:1)

您可能需要检查是否正确创建了json。调用json_decode后,生成的数组可能包含嵌套数组,如

$jsonArray_new = array (
    array(
        'your JSON data here as key=>value pairs'
    ),
);

因此禁止您按键获取数组值。

在使用解码数据之前,我建议您进行简单empty()检查,因为解码可能会失败,而$jsonArray_new可能会false作为值。

旁注:您的代码需要重构。太多的潜在失败点。