从wp-config.php文件中我需要获取数据库名称,用户名和密码值,而不包括wp-config文件,并将它们分配给三个单独的变量以供进一步使用。
define('DB_NAME', 'somedb');
define('DB_USER', 'someuser');
define('DB_PASSWORD', 'somepass');
我的脚本将在同一个文件夹中。不,我不想使用任何WordPress功能。
答案 0 :(得分:0)
如果您确实不想包含该文件,请在评论中提及,
我们可以使用file()
将文件内容读入数组。
迭代每一行并应用一些清理,直到我们得到一种我们可以使用的格式:
<?php
$config = file('wp-config.php');
$dbLines = [];
foreach($config as $line){
if (stristr($line,"define('DB_")!==FALSE){
$dbLines[] = $line;
}
}
array_walk($dbLines, 'cleanup');
// apply the cleanup() function to all members of the array, basically to each line
function cleanup(&$value){
// replace the leading 'define(' and trailing closing bracket
$value = str_replace(
array("define(",");"),'',$value
);
$value = preg_replace('#\s+//(.*)#','',$value); // remove the comments
}
// at this point we have a csv structure with a single quote as the delimiter
// comma+space as a separator
$dbConfig = [];
foreach ($dbLines as $dbline){
// read the line into separate variables and build an array
list($key,$value) = (str_getcsv($dbline,', ',"'"));
$dbConfig[$key] = $value;
}
print_r($dbConfig);
这将输出
Array
(
[DB_NAME] => putyourdbnamehere
[DB_USER] => usernamehere
[DB_PASSWORD] => yourpasswordhere
[DB_HOST] => localhost
[DB_CHARSET] => utf8
[DB_COLLATE] =>
)
如果要从数组中访问单个元素,只需
print $dbConfig['DB_HOST'];