PHP:检查XML节点是否存在带有属性 [英] PHP: Check if XML node exists with attribute

查看:102
本文介绍了PHP:检查XML节点是否存在带有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚这一点.我有以下XML文件:

I can't seem to figure this one out. I have the following XML file:

<?xml version="1.0" encoding="UTF-8"?>
<targets>
  <showcases>
    <building name="Big Blue" />
    <building name="Shiny Red" />
    <building name="Mellow Yellow" />
  </showcases>
</targets>

我需要能够测试是否存在具有给定名称的<building> 节点.我似乎可以在Google上找到的所有内容都告诉我执行以下操作:

I need to be able to test whether or not a <building> node exists with a given name. Everything I seem to find on Google tells me to do something like the following:

$xdoc->getElementsByTagName('building')->item(0)->getAttributeNode('name')

...但是如果我理解正确,那不是仅测试第一个<building>节点吗? item(0)?我需要为此使用XQuery吗?

... but if I understand that correctly, doesn't that only test the first <building> node? item(0)? Do I need to use XQuery for this?

我将感谢您的帮助!谢谢!

I'd appreciate some help! Thanks!

推荐答案

我建议以下内容(使用ext/simplexml和XPath的PHP):

I'd suggest the following (PHP using ext/simplexml and XPath):

$name = 'Shiny Red';
$xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?>
<targets>
  <showcases>
    <building name="Big Blue" />
    <building name="Shiny Red" />
    <building name="Mellow Yellow" />
  </showcases>
</targets>');
$nodes = $xml->xpath(sprintf('/targets/showcases/building[@name="%s"]', $name);
if (!empty($nodes)) {
    printf('At least one building named "%s" found', $name);
} else {
    printf('No building named "%s" found', $name);
}

这篇关于PHP:检查XML节点是否存在带有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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