如何在Python中读取PHP文件中的PHP数组

4 投票
3 回答
5058 浏览
提问于 2025-04-17 01:18

假设我们想要用PHP来制作一个Python的配置读取器。

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'}

在Python中这样做可能吗?

3 个回答

0

这是对Eugene的一种变体:

在我的情况下,php文件只是设置了一些变量,并没有返回一个数组。

所以,我必须在进行json_encode之前先包含这个文件;然后再对特定的变量进行编码。这是为了读取ownCloud的version.php文件。可以查看这个链接:https://github.com/owncloud/core

例如:

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))
1
  1. 用PHP脚本解析配置文件

  2. 使用JSON格式把配置变量保存到一个文件里

  3. 通过os.system()在Python中执行解析器

  4. 在Python中读取JSON文件

8
from subprocess import check_output
import json

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

这里的 config.php 文件会返回一个数组:

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

撰写回答