Adam Ramadhan
Adam Ramadhan

Reputation: 22810

how to read a php array from php file in python

lets say we want to make a python config reader from php.

config.php

$arr = array(
    'a config',
    'b config',
    'c config => 'with values'
)

$arr2 = array(
    'a config',
    'b config',
    'c config => 'with values'
)

readconfig.py

f = open('config.php', 'r')
// somehow get the array then turns it into pythons arr1 and arr2

print arr1
# arr1 = {'a config', 'b config', 'c config': 'with values'}

print arr2
# arr2 = {'a config', 'b config', 'c config': 'with values'}

is this possible in python ?

Upvotes: 4

Views: 5205

Answers (3)

jksinton
jksinton

Reputation: 1

As a variation of Eugenes:

In my situation the php file only set variables, it did not return an array.

Thus, I had to perform the include before the json_encode; then, encode particular variables. This was for reading version.php for ownCloud. See https://github.com/owncloud/core

E.g.

vFileName=configDict['ocDir']+'/version.php'
cmd=['/usr/bin/php','-r','include "'+vFileName+'"; echo json_encode(array($OC_Version,$OC_VersionString));']
ocVersion, ocVersionString=json.loads(subprocess.check_output(cmd))

Upvotes: 0

Eugene Leonovich
Eugene Leonovich

Reputation: 924

from subprocess import check_output
import json

config = check_output(['php', '-r', 'echo json_encode(include "config.php");'])
config = json.loads(config)

where config.php returns an array:

return [
    'param1' => 'value1',
    'param2' => 'value2',
];

Upvotes: 9

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83398

  1. Parse config usin PHP script

  2. Save config vars to a file using JSON

  3. Execute parser from Pytson using os.system()

  4. Read JSON file in Python

Upvotes: 1

Related Questions