简体   繁体   English

将数组 object 从 PHP 传递到 Python

[英]Passing array object from PHP to Python

This is my code so far到目前为止,这是我的代码

    $dataraw = $_SESSION['image'];
    $datagambar = json_encode($dataraw);

    echo '<pre>';
    print_r($dataraw);
    echo '</pre>';

    print($escaped_json);

    $type1 = gettype($dataraw);
    print($type1);

    $type2 = gettype($datagambar);
    print($type2);

This is $dataraw output, the type is array这是$dataraw output,类型是数组

Array
(
    [0] => Array
        (
            [FileName] => 20221227_202035.jpg
            [Model] => SM-A528B
            [Longitude] => 106.904251
            [Latitude] => -6.167665
        )

    [1] => Array
        (
            [FileName] => 20221227_202157.jpg
            [Model] => SM-A528B
            [Longitude] => 106.9042428
            [Latitude] => -6.1676580997222
        )

)

This is $datagambar output, the type is string这是$datagambar output,类型是string

[{"FileName":"20221227_202035.jpg","Model":"SM-A528B","Longitude":106.904251,"Latitude":-6.167665},{"FileName":"20221227_202157.jpg","Model":"SM-A528B","Longitude":106.9042428,"Latitude":-6.167658099722223}]

Pass to python传给python

echo shell_exec("D:\Anaconda\python.exe D:/xampp/htdocs/Klasifikasi_KNN/admin/test.py $datagambar");

This is my python test.py这是我的 python test.py

json_list = []
escaped_json1 = sys.argv[1]

# this is working but its only a string of array json
# print(escaped_json1) 
# this is working but its only a string of array json

json_list.append(json.loads(escaped_json1))
parsed_data = json.loads(escaped_json1) 
print(json_list)
print(parsed_data)

When i do print(escaped_json1) it display a string of array json from php($datagambar).当我执行 print(escaped_json1) 时,它显示来自 php($datagambar) 的数组 json 的字符串。

python output: python output:

Hello world has been called [{"FileName":"20221227_202035.jpg","Model":"SM-A528B","Longitude":106.904251,"Latitude":-6.167665},{"FileName":"20221227_202157.jpg","Model":"SM-A528B","Longitude":106.9042428,"Latitude":-6.167658099722223}]

I use apache as my server with phpmyadmin and anaconda.我使用 apache 作为我的服务器,phpmyadmin 和 anaconda。

T tried using print(type(escapedjson1)) or print(type(escapedjson1)) but it doesn't display the type T 尝试使用 print(type(escapedjson1)) 或 print(type(escapedjson1)) 但它不显示类型

json.loads didn't change the type of data to python array json.loads没有改变数据类型为python数组

How to loads it and make the string array into a variable array so i can call it and convert it to dataframe?.如何加载它并将字符串数组变成一个变量数组,以便我可以调用它并将其转换为 dataframe?。

You just need to enclose in single quotes the argument to python:您只需要将 python 的参数用单引号引起来:

shell_exec("python3 test.py '$json'");

Example例子

file.php文件.php

$data =
[
    [
        "FileName" => "20221227_202035.jpg",
        "Model" => "27_202035.jpg",
        "Longitude" => 106.90425,
        "Latitude" => 106.90425
    ],
    [
        "FileName" => "20221227_202157.jpg",
        "Model" => "SM-A528B",
        "Longitude" => 106.9042428,
        "Latitude" => -6.1676580997222
    ]
];

$json = json_encode($data);

// note: arg '$json' is single-quoted
echo shell_exec("python3 test.py '$json'");

test.py测试.py

import sys
import json
from pandas import json_normalize

data = sys.argv[1]

dict = json.loads(data)
df2 = json_normalize(dict) 

print(df2)

Output Output

              FileName     Model   Longitude  Latitude
0  20221227_202035.jpg  SM-A528B  106.904251 -6.167665
1  20221227_202157.jpg  SM-A528B  106.904243 -6.167658

See: Escaping double qoutes when sending JSON as argument in python program请参阅: Escaping 在 python 程序中发送 JSON 作为参数时的双引号

Update: A Completely different approach更新:一种完全不同的方法

There is a difficulty with the PHP script JSON-encoding a structure to produce a JSON string and then passing it as a command line argument since the string needs to be placed in double quotes because there can be embedded spaces in the encoded string. PHP 脚本 JSON 编码结构以生成 JSON 字符串,然后将其作为命令行参数传递,因为字符串需要放在双引号中,因为编码字符串中可以嵌入空格。 But the string itself can contain double quotes as start of string characters and within such a string.但是字符串本身可以包含双引号作为字符串字符的开头并包含在这样的字符串中。 Confused?使困惑? Who wouldn't be?谁不会呢?

There is no problem however with writing such a string to a file and having the Python program read it in and decode it.但是,将这样的字符串写入文件并让 Python 程序将其读入并解码是没有问题的。 But we don't want to have to deal with temporary files.但是我们不想处理临时文件。 So the solution is to pipe the data to the Python program where it can then be read in as stdin所以解决方案是pipe数据到 Python 程序,然后它可以作为标准输入读入

Let's assume your array looks like:假设您的数组如下所示:

$arr =
[
    [
        "FileName" => "\"\\  \nRon's20221227_202035.jpg",
        "Model" => "27_202035.jpg",
        "Longitude" => 106.90425,
        "Latitude" => 106.90425
    ],
    [
        "FileName" => "20221227_202157.jpg",
        "Model" => "SM-A528B",
        "Longitude" => 106.9042428,
        "Latitude" => -6.1676580997222
    ]
];

Note that I have modified your example slightly so that the first FileName field contains a " character, a ' character, an escape sequence \n representing the newline character and finally some spaces. Although your example does not contain these characters or some other escape sequence, I would like to be able to handle such a condition should it arise. This solution should work with such input.请注意,我稍微修改了您的示例,以便第一个FileName字段包含一个"字符、一个'字符、一个转义序列\n表示换行符,最后是一些空格。尽管您的示例不包含这些字符或其他一些转义序列,我希望能够处理这种情况。这个解决方案应该适用于这样的输入。

PHP File PHP 文件

<?php
$arr =
[
    [
        "FileName" => "\"\\  \nRon's20221227_202035.jpg",
        "Model" => "27_202035.jpg",
        "Longitude" => 106.90425,
        "Latitude" => 106.90425
    ],
    [
        "FileName" => "20221227_202157.jpg",
        "Model" => "SM-A528B",
        "Longitude" => 106.9042428,
        "Latitude" => -6.1676580997222
    ]
];

// Encode string as JSON:
$json = json_encode($arr);

// Pipe the JSON string to the Python process's stdin and
// read the result from its stdout:
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w")   // stdout is a pipe that the child will write to
);
$process = proc_open("python3 test.py", $descriptorspec, $pipes);

// Pipe the input for the Python program and close the pipe:
fwrite($pipes[0], $json);
fclose($pipes[0]);

// Read the result from the Python program and close its pipe
$result = stream_get_contents($pipes[1]);
fclose($pipes[1]);

# Now that we have closed the pipe, we can close the process:
$return_code = proc_close($process);

echo $result;

test.py测试.py

import json
import sys

# Read from stdin:
json_string = sys.stdin.read()
arr = json.loads(json_string)
# print each dictionary of the array:
for d in arr:
    print(d)

Prints:印刷:

{'FileName': '"\\  \nRon\'s20221227_202035.jpg', 'Model': '27_202035.jpg', 'Longitude': 106.90425, 'Latitude': 106.90425}
{'FileName': '20221227_202157.jpg', 'Model': 'SM-A528B', 'Longitude': 106.9042428, 'Latitude': -6.1676580997222}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM