使用PHP解析XML时,常用simplexml_load_string,缺省是一个SimpleXMLElement的包装函数,今天不说simplexml_load_string,只说SimpleXMLElement。
本文以Android软件中的AndroidManifest.xml文档为例,先看一下演示文档的内容:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="PACKAGE" android:versionName="VERSIONNAME"> <application android:icon="ICON" android:label="LABEL" android:name="NAME"> </application> <uses-sdk android:minSdkVersion="1" /> <uses-sdk android:maxSdkVersion="2" /> <uses-permission android:name="android.permission.FOO"></uses-permission> <uses-permission android:name="android.permission.BAR"></uses-permission> </manifest>
BTW:APK软件中的AndroidManifest.xml文档是二进制编码的,可以用APKTool还原。
我们的目标是解析若干属性:如package, versionName, icon, label, name等,代码如下:
<?php $xml = new SimpleXMLElement(file_get_contents('AndroidManifest.xml')); $nodes = $xml->xpath('/manifest'); var_dump((string)$nodes[0]->attributes()->package); var_dump((string)$nodes[0]->attributes('android', true)->versionName); $nodes = $xml->xpath('/manifest/application'); var_dump((string)$nodes[0]->attributes('android', true)->icon); var_dump((string)$nodes[0]->attributes('android', true)->label); var_dump((string)$nodes[0]->attributes('android', true)->name); $nodes = $xml->xpath('/manifest/uses-sdk'); foreach ($nodes as $node) { foreach ($node->attributes('android', true) as $attribute => $value) { var_dump($attribute, (string)$value); } } $nodes = $xml->xpath('/manifest/uses-permission'); foreach ($nodes as $node) { foreach ($node->attributes('android', true) as $attribute => $value) { var_dump($attribute, (string)$value); } } ?>
因为只是演示,所以代码有点冗余,大家留意命名空间的使用,多余的话我就不说了。
Pingback引用通告: 網站製作學習誌 » [Web] 連結分享
I see you share interesting things here, you can earn some additional
money, your blog has huge potential, for
the monetizing method, just type in google – K2 advices how to monetize a website