4

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 ?

2
  • 1
    use ini or json or yaml or xml Commented Sep 3, 2011 at 0:27
  • 2
    If you write a parser for the PHP array syntax then it is possible. I'd highly suggest you to use a portable format such as YAML or even a file with plain key=value lines. Commented Sep 3, 2011 at 0:27

3 Answers 3

9
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',
];
Sign up to request clarification or add additional context in comments.

Comments

1
  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

1 Comment

i still don`t get the 2. and 3. can you explain it more ? thanks!
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.