还在苦苦敲代码开发APP?你out啦! 试试积木搭建APP吧~

实例演示SimpleXMLElement的用法

来源:个人博客     2015-11-23 15:57:30    人气:     我有话说( 0 人参与)

使用PHP解析XML时,常用simplexml_load_string,缺省是一个SimpleXMLElement的包装函数,今天不说simplexml_load_string,只说SimpleXMLEle...

使用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);
    }
}

?>

因为只是演示,所以代码有点冗余,大家留意命名空间的使用,多余的话我就不说了。

simplexml_load_string SimpleXMLElement

本文源自互联网,采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可,
版权归原作者,如有问题请联系service@tsingfun.com (编辑:admin)
分享到: