【问题标题】:Parse XML in PHP by specific attribute通过特定属性在 PHP 中解析 XML
【发布时间】:2011-10-20 04:33:50
【问题描述】:

我需要获取<name><URL> 标签的值,其中subtype="mytype"。如何在PHP 中做到这一点? 我想要结果中的文档名称和 test.pdf 路径。

<?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>

【问题讨论】:

  • php.net/manual/en/book.xml.php">XML Parser 扩展是一个选项吗?
  • 我不确定是谁标记了你——或者为什么——但菲尔是绝对正确的。 SimpleXML(使用 XPath)是要走的路:w3schools.com/php/php_xml_simplexml.asp
  • @paulsm4:反对票来自我。原因是:没有显示研究成果,没有提供代码,并且可以通过 google 或 SO 搜索功能找到答案。

标签: php xml xml-parsing


【解决方案1】:

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

【讨论】:

  • @dayana 我假设您的 XML 在字符串变量中。我已更新我的答案以使用文件
  • @dayana 随时accept this answer。当你在做的时候,接受你其他问题的一些答案
【解决方案2】:

PHP 5.1.2+ 有一个名为SimpleXML 的扩展默认启用。它对于解析格式良好的 XML 非常有用,就像您上面的示例一样。

首先,创建一个SimpleXMLElement 实例,将XML 传递给它的构造函数。 SimpleXML 将为您解析 XML。 (这就是我感受到 SimpleXML 优雅的地方——SimpleXMLElement 是整个库的唯一类。)

$xml = new SimpleXMLElement($yourXml);

现在,您可以轻松地遍历 XML,就像它是任何 PHP 对象一样。属性可作为数组值访问。由于您正在寻找具有特定属性值的标签,我们可以编写一个简单的循环来遍历 XML:

<?php
$yourXml = <<<END
<?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>
END;

// Create the SimpleXMLElement
$xml = new SimpleXMLElement($yourXml);

// Store an array of results, matching names to URLs.
$results = array();

// Loop through all of the tests
foreach ($xml->required[0]->item as $item) {
    if ( ! isset($item['subtype']) || $item['subtype'] != 'mytype') {
        // Skip this one.
        continue;
    }

    // Cast, because all of the stuff in the SimpleXMLElement is a SimpleXMLElement.
    $results[(string)$item->name] = (string)$item->url;
}

print_r($results);

codepad 中测试正确。

希望这会有所帮助!

【讨论】:

    【解决方案3】:

    您可以使用 XML Parser 或 SimpleXML。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 2012-06-08
      • 2012-04-01
      • 1970-01-01
      相关资源
      最近更新 更多