PHP 中最内部子节点的 XML 解析



我正在解析一个XML文件,谁能帮我解析最后一个也是最里面的子节点。

<section index="2.2.4" title="Recommendation" ref="RECOMMENDATION">
<text>DWS strongly recommends that all authentication credentials should be configured with a strong password.</text>
<text>DWS recommends that:</text>
<list type="bullet">
<listitem>passwords should be at least eight characters in length;</listitem>
<listitem>characters in the password should not be repeated more than five times;</listitem>
<listitem>passwords should include both upper case and lower case characters;</listitem>
<listitem>passwords should include numbers;</listitem>
<listitem>passwords should include punctuation characters;</listitem>
<listitem>passwords should not include the username;</listitem>
<listitem>passwords should not include a device's name, make or model;</listitem>
<listitem>passwords should not be based on dictionary words.</listitem>
</list>
<text>Notes for Cisco Catalyst Switch devices:</text>
<text>The following commands can be used on Cisco Catalyst Switch devices to set the enable password, create a local user with a password and to delete a local user:<code><command>enable secret <cmduser>password</cmduser></command>
<command>username <cmduser>user</cmduser> secret <cmduser>password</cmduser></command>
<command>no username <cmduser>user</cmduser></command>
</code></text>
</section>

任何人都可以帮助解析 PHP 中最里面的子节点吗?

<code><command>enable secret <cmduser>password</cmduser></command>
<command>username <cmduser>user</cmduser> secret <cmduser>password</cmduser></command>
<command>no username <cmduser>user</cmduser></command>
</code></text>
</section>

尤其是这个命令cmd用户命令???

根据您想要的数据部分,您可以将其加载到 SimpleXML 中,然后使用 XPath 搜索<code>元素,因此基本版本将是...

$fileName = "out.xml";
$xml = simplexml_load_file($fileName);
$code = $xml->xpath("//code");
echo "command=".trim($code[0]->command).PHP_EOL;
echo "cmduser=".trim($code[0]->command->cmduser).PHP_EOL;
echo "cmduser=".trim($code[0]->command[1]->cmduser[0]).PHP_EOL;

会给你(带有测试数据(...

command=enable secret
cmduser=password
cmduser=user

或者,如果您想同时使用用户和密码来选择<command>元素,则可以使用 XPath 选择具有 2 个<cmduser>元素的元素...

$code = $xml->xpath("//code/command[count(cmduser)=2]");
echo "cmduser1=".trim($code[0]->cmduser[0]).PHP_EOL;
echo "cmduser2=".trim($code[0]->cmduser[1]).PHP_EOL;

哪个给

cmduser1=user
cmduser2=password

最新更新