如何获取角色节点

How to get the role nodes

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

或者有没有办法更动态地使用角色节点?

我的XML:

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

还有我的 php-code,我用它从上方经历 XML: (在 output_roles-function 中 $roles 变量只是第一个 child,但我需要两个 childs)(->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表达式,例如

$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

如果您想要获得所有最内层角色的祖先角色,您可以使用 xpath 来实现。例如:

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

xpath return 以上 <role role="Administrator"> 下的所有 <role> 没有子元素 <role>,换句话说,最里面的 <role> 元素.