2011-10-20 97 views
1

我需要获得<name><URL>标记的值,其中subtype="mytype"。PHP如何实现? 我想在我的结果中的文档名称和test.pdf路径。在PHP中通过特定属性解析XML

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

我不确定是谁标记了你 - 或者为什么 - 但是菲尔绝对正确。 SimpleXML(使用XPath)是要走的路:http://www.w3schools.com/php/php_xml_simplexml.asp – paulsm4

+0

@ paulsm4:downvote来自我。原因是:没有显示研究工作,没有提供代码,可以通过谷歌或SO搜索功能找到答案。 – vstm

+0

XML Parser扩展是一个选项吗? – Unsigned

回答

3

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

什么是$ xmlString? – dayana

+0

它是.xml文件路径吗? – dayana

+0

@dayana我认为你的XML是一个字符串变量。我已经更新了我的答案以使用文件 – Phil

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

希望这会有所帮助!

0

您可以使用XML解析器或SimpleXML。