且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP:检查XML节点是否存在带有属性

更新时间:2023-02-23 18:50:52

我建议以下内容(使用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);
}