这是XML文件
<theme name="front">
<layouts url="/administrator" tpl="default.html" >
<templates>
<login url="/login" tpl="login.html"></login>
<dashboard url="/" tpl="dashboard.html"></dashboard>
<contact url="/contacts" tpl="contact.html" >
<templates>
<add url="/add"></add>
<edit url="/modify" ></edit>
<remove url="/remove" ></remove>
<bulk_view url="/bulk-view"></bulk_view>
</templates>
</contact>
<help url="/help" tpl="content.html"></help>
<settings url="/settings" tpl="content.html"></settings>
</templates>
</layouts>
</theme>
我有两个问题:
我如何使树url数组可能像下面。
/administrator /administrator/ /administrator/login /administrator/contacts /administrator/contacts/add /administrator/contacts/modify /administrator/contacts/bulk-view /administrator/help /administrator/settings
我有一个字符串URL匹配像
/administrator/contacts/add
。我怎么能得到SimpleXMLElement对象匹配这个字符串URL?
最好通过查询文档来查找要查找的信息。对于XML,最好使用Xpath。
例如,如果您想获得所有具有url属性的元素,查询是:
//*[@url]
如果您现在考虑在文档中任何此类元素的,您可以在ancestor-or-self xpath-axis:
上以文档顺序检索所有url属性。ancestor-or-self::*/@url
到目前为止,这只是针对裸xpath查询。当使用PHP的XML库(这里是示例性的SimpleXML)
包装在PHP代码中时,就会出现这种情况。<?php
/**
* Get Url match traversing xml simplexml_load_file (Example #1)
*
* @link http://stackoverflow.com/q/31848077/367456
*/
$string = <<<XML
<theme name="front">
<layouts url="/administrator" tpl="default.html">
<templates>
<login url="/login" tpl="login.html"></login>
<dashboard url="/" tpl="dashboard.html"></dashboard>
<contact url="/contacts" tpl="contact.html">
<templates>
<add url="/add"></add>
<edit url="/modify"></edit>
<remove url="/remove"></remove>
<bulk_view url="/bulk-view"></bulk_view>
</templates>
</contact>
<help url="/help" tpl="content.html"></help>
<settings url="/settings" tpl="content.html"></settings>
</templates>
</layouts>
</theme>
XML;
$xml = simplexml_load_string($string);
foreach ($xml->xpath('//*[@url]') as $urlElement) {
echo implode("", $urlElement->xpath('ancestor-or-self::*/@url')), "'n";
}
结果是(也是:online demo):
/administrator
/administrator/login
/administrator/
/administrator/contacts
/administrator/contacts/add
/administrator/contacts/modify
/administrator/contacts/remove
/administrator/contacts/bulk-view
/administrator/help
/administrator/settings
要匹配这些url中的任何一个,您需要查看它是否是您要查找的url:
$search = '/administrator/contacts/add';
foreach ($xml->xpath('//*[@url]') as $urlElement) {
$url = implode("", $urlElement->xpath('ancestor-or-self::*/@url'));
if ($url !== $search) {
continue;
}
// found!
$urlElement->asXML('php://output');
break;
}
输出第一个匹配的元素:
<add url="/add"/>