通过特定属性解析 PHP 中的 XML [英] Parse XML in PHP by specific attribute

查看:29
本文介绍了通过特定属性解析 PHP 中的 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取 标签的值,其中 subtype="mytype".怎么做在 PHP 中?我希望在结果中包含文档名称和 test.pdf 路径.

I need to get <name> and <URL> tag's value where subtype="mytype".How can do it in PHP? I want document name and test.pdf path in my result.

<?xml version="1.0" encoding="UTF-8"?>
    <test>
        <required>
            <item type="binary">
                <name>The name</name>
            <url visibility="restricted">c:/temp/test/widget.exe</url>
            </item>
            <item type="document" subtype="mytype">
                <name>document name</name>
            <url visiblity="visible">c:/temp/test.pdf</url>
            </item>
        </required>
    </test>

推荐答案

使用 SimpleXML 和 XPath,例如

$xml = simplexml_load_file('path/to/file.xml');

$items = $xml->xpath('//item[@subtype="mytype"]');
foreach ($items as $item) {
    $name = (string) $item->name;
    $url = (string) $item->url;
}

这篇关于通过特定属性解析 PHP 中的 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆