问题如下:
我有一个包含数据的xml文件,我正在寻找一小部分数据以将其写入新文件:内容已根据请求缩短:
如果type = dhcp-client,则为摘录:
<deviceconfig>
<system>
<type>
<dhcp-client>
<send-hostname>yes</send-hostname>
</dhcp-client>
</type>
<hostname>Firewall</hostname>
</system>
</deviceconfig>
如果type = static,则为摘录
<deviceconfig>
<system>
<type>
<static/>
</type>
<hostname>Firewall</hostname>
<permitted-ip>
<entry name="192.168.0.0/24"/>
</permitted-ip>
<ip-address>192.168.0.2</ip-address>
<netmask>255.255.255.0</netmask>
<default-gateway>192.168.0.1</default-gateway>
</system>
<network>
<interface>
<ethernet>
<entry name="ethernet1/1">
<layer3>
<ip>
<entry name="192.168.0.5/24"/>
</ip>
</layer3>
</entry>
</ethernet>
</interface>
<virtual-router>
<entry name="default">
<routing-table>
<ip>
<static-route>
<entry name="default-route">
<nexthop>
<ip-address>192.168.0.1</ip-address>
</nexthop>
<interface>ethernet1/4</interface>
<destination>0.0.0.0/0</destination>
</entry>
</static-route>
</ip>
</routing-table>
</entry>
</virtual-router>
</network>
四个相关值在“系统”标签中是唯一的(或不存在),<system></system>
例如ip-address之类的东西可能会在其他地方再次出现,<system></system>
但我只是检查系统内部的那些,如果类型不是静态的,则不要显示,我对其进行设置到dhcp-client
这是我需要的结果,如果类型为dhcp,则在文件中:
type=dhcp-client
如果类型是静态的,这就是我需要的结果:
type=static
ip-address=192.168.0.2
default-gateway=192.168.0.1
netmask=255.255.255.0
我不确定如何有效地完成此工作并将其集成到现有的PHP文件中(因此可以使用exec或更好地使用php)。
我还限于默认情况下在ubuntu服务器系统上安装的工具,并且将无法使用其他软件包。
PS:这实际上是整个/完整的用例,除了这两个示例外,我将不需要产生其他输出。感谢您的帮助或指点:)
好吧,我自己找到了答案...
实际上,在PHP中要比没有它简单得多...
确实花了我几个小时才能完成^^
#load the file as simplexml object and then switch into system
#https://www.w3schools.com/php/func_simplexml_load_file.asp
$xml=simplexml_load_file('./myfile') or die("Error: Cannot create object");
$xml=$xml->system
#put the whole string(s) into a variable, getname gets the name of the object itself if it exists
#https://www.w3schools.com/php/func_simplexml_getname.asp
$output='type=' . $xml -> type -> static -> getName() . $xml -> type -> {'dhcp-client'} -> getName() . "\nip-address=" . $xml -> {'ip-address'} . "\ndefault-gateway=" . $xml -> {'default-gateway'} . "\nnetmask=" . $xml -> netmask;
#write the output into a file
#https://www.w3schools.com/php/func_filesystem_file_put_contents.asp
file_put_contents('./myoutputfile', $output );
这为我的第一个代码段提供了以下输出(如果没有给出值,则后三行就可以了,否则我可以检查它们是否首先存在):
type=dhcp-client
ip-address=
default-gateway=
netmask=
第二个代码段的输出如下:
type=static
ip-address=192.168.0.2
default-gateway=192.168.0.1
netmask=255.255.255.0
谢谢大家的帮助:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句