如何获取角色节点


How to get the role nodes

如何获取"Blog-Autor"-Role和"Kommentar-Manager"-Role的角色节点?

或者是否有一种方法可以更动态地使用角色节点?

我的XML:

<roles>
    <role role="Administrator">
        <role role="Account Manager">
            <role role="Blog-Autor"/>
            <role role="Kommentar-Manager"/>
        </role>
    </role>
</roles>

和我的php代码,我通过从上面的XML:(在output_roles-function中,$roles变量只是第一个子变量,但我需要两个子变量)(->children()没有帮助)

public function User_Roles() {
        $User_Type = $_SESSION["User_Type"];
        $xml_path = "./blog_config/blog_roles.xml";
        $xml_file = simplexml_load_file($xml_path);
        foreach ($xml_file->role as $role) {
            $role_attributes = $role->attributes();
            $user_role = (string) $role_attributes->role;
            if ($user_role == $User_Type) {
                $this->output_roles($role);
            }
        }
    }
private function output_roles($role) {
    foreach ($role as $current_role) {
        $role_ = $current_role->attributes();
        $role_type = (string) $role_->role;
        echo "<tr>";
        echo "<td><b>" . $role_type . "</b></td>";
        echo "</tr>";
        $roles = $role->role;
        $x = is_array($roles);
        if (is_array($current_role->role)) {
            $this->output_roles($current_role->role);
        }
    }
}

如果您想让所有最内部的角色都被赋予一个祖先角色,您可以使用xpath来实现。例如:

$User_Type = "Administrator";
$roles = $xml_file->xpath("//role[@role='$User_Type']//role[not(role)]");

上面的xpath返回<role role="Administrator">下所有没有子元素<role><role>,即最里面的<role>元素。

只需使用XPath表达式,例如

$matches = $xml_file->xpath('//role[@role="Blog-Autor"]');

当然,您可以更具体地使用路径,例如

$matches = $xml_file->xpath('/role[@role="Administrator"]/role[@role="Account Manager"]/role[@role="Blog-Autor"]');

但这应该会让你继续。

参见SimpleXMLElement::xpath