Skip to content Skip to sidebar Skip to footer

Passing A Python List To Php

I'm very new to php and I've been spending quite some type understanding how to pass arguments from Python to php and conversely. I now know how to pass single variables, but I am

Solution 1:

For instance:

myscript.py

import json

D = {'foo':1, 'baz': 2}

print json.dumps(D)

myscript.php

<?php$result = json_decode(exec('python myscript.py'), true);
echo$result['foo'];

Solution 2:

You're using stdin / stdout to transfer the data between the programs, that means you'll have to encode your structure somehow in order to let your receiving program parse the elements.

The simplest thing would be to have python output something like a comma separated list

Adam,Barry,Cain

and use

$result = explode(exec('python myscript.py'));

on the php side to turn your string data back into an array.

If the data is unpredictable (might contain commas) or more structured (more than just a simple list) then you should go for something like json as suggested by Krab.

Solution 3:

Apparently your question was misleading. Was redirected here thinking this a solution for converting python lists to php array.

Posting a naive solution for ones wanting to convert lists to php array.

// Sample python list $data= '[["1","2","3","4"],["11","12","13","14"],["21","22","23","24"]]';

// Removing the outer list brackets$data=  substr($data,1,-1);

$myArr= array();
// Will get a 3 dimensional array, one dimension for each list$myArr=explode('],', $data);

// Removing last list bracket for the last dimensionif(count($myArr)>1)
$myArr[count($myArr)-1] = substr($myArr[count($myArr)-1],0,-1);

// Removing first last bracket for each dimenion and breaking it down further
foreach ($myArras$key=>$value) {
 $value= substr($value,1);
 $myArr[$key] = array();
 $myArr[$key] = explode(',',$value);
}

//OutputArray
(
[0] =>Array
    (
        [0] =>"1"
        [1] =>"2"
        [2] =>"3"
        [3] =>"4"
    )

[1] =>Array
    (
        [0] =>"11"
        [1] =>"12"
        [2] =>"13"
        [3] =>"14"
    )

[2] =>Array
    (
        [0] =>"21"
        [1] =>"22"
        [2] =>"23"
        [3] =>"24"
    )

)

Solution 4:

$str = "[u'element1', u'element2', 'element3']";

$str = str_replace( array("u'", "[", "]"), array("'", ""), $str );
$strToPHPArray = str_getcsv($str, ",", "'");
print_r( $strToPHPArray );

Outputs

Array
(
    [0] => element1
    [1] => element2
    [2] => element3
)

Post a Comment for "Passing A Python List To Php"