解析PHP文件以获取参数数组

xwbd5t1u  于 2023-09-29  发布在  PHP
关注(0)|答案(1)|浏览(109)

我有一个PHP文件,内容如下:

<?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

$APPLICATION->IncludeComponent(
    "hoo:account",
    "hoo",
    array(
        "COMPONENT_TEMPLATE" => "hoo",
        "ACCOUNT_URL" => "/account/",
        "LOG_IN_URL" => "/log-in/",
        "FIELDS_REQUIRED" => array(
            0 => "FIRST_NAME",
            1 => "LAST_NAME",
            2 => "BIRTHDAY",
        ),
        "FIELDS_VALIDATED" => array(
            0 => "BIRTHDAY",
            1 => "COMPANY_VAT_CODE",
        ),
        "AGE_MIN" => "18",
        "AGE_MAX" => "180",
        "COMPANY_VAT_CODE_VALIDATION_SERVICE_CACHE_TTL" => "86400",
        "COMPANY_VAT_CODE_VALIDATION_SERVICE_SERVICE_UNAVAILABLE_ERROR" => "Y",
        ...
    ), false);

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
?>

不知何故,我需要解析这个文件,以便获得一个带有参数的关联数组,以便在代码中的其他地方使用它。请给予我一些想法和代码示例如何实现这一目标。
提前感谢!

ds97pgxw

ds97pgxw1#

使用Tokenizer,我可以编写一个小型解析器来实现我的目标:

<?
$tokens = token_get_all();

$componentName = "hoo:account";

$arParams = array();

foreach ($tokens as $tokenKey => $token) {
    if (is_array($token)) {
        if (_getTokenName($token) == "T_STRING" &&
            _getToken($tokens, $tokenKey + 3) == $componentName
        ) {
            $isComponent = true;
        } elseif (_getTokenName($token) == "T_STRING" &&
                  _getToken($tokens, $tokenKey + 3) != $componentName
        ) {
            $isComponent = false;
        }

        if ($isComponent) {
            if (_getTokenName($token) == "T_DOUBLE_ARROW") {
                if (_getTokenName($tokens[$tokenKey - 2]) == "T_CONSTANT_ENCAPSED_STRING") {
                    if (_getTokenName($tokens[$tokenKey + 2]) == "T_ARRAY") {
                        $key = _getToken($tokens, $tokenKey - 2);
                    } else {
                        $arParams[_getToken($tokens, $tokenKey - 2)] = _getToken($tokens, $tokenKey + 2);
                    }
                } elseif (_getTokenName($tokens[$tokenKey - 2]) == "T_LNUMBER") {
                    $arParams[$key][] = _getToken($tokens, $tokenKey + 2);
                }
            }
        }
    }
}

function _getTokenName(array $token): string {
    return token_name($token[0]);
}

function _getToken(array $tokens, int $key): int | string {
    return trim($tokens[$key][1], "\"");
}
?>

相关问题