简体   繁体   English

如何获取PHP中XML元素内的属性的值?

[英]How to get the value of an attribute inside an XML element in PHP?

How do I get the value of an attribute inside an XML element? 如何获取XML元素内的属性的值?

For Example: I want to get the value of attribute category . 例如:我想获取属性category的值。

<bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>

Use the SimpleXML extension: 使用SimpleXML扩展名:

<?php
$xml = '<bookstore>
<book category="cooking">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>
</bookstore>';
$doc = simplexml_load_string($xml);
echo $doc->book->attributes()->category; // cooking
echo $doc->book->title.PHP_EOL; // Everyday Italian
echo $doc->book->title->attributes()->lang.PHP_EOL; // en

Demo 演示版

Every element will be set as a property on the root object for you to access directly. 每个元素都将被设置为根对象上的属性,以供您直接访问。 In this particular case, you can use attributes() to get the attributes of the book element. 在这种情况下,可以使用attributes()获取book元素的属性。

You can see in the example that you can keep going through the levels in the same way: to get to the lang attribute in book , use $doc->book->title->attributes()->lang . 您可以在示例中看到,可以以相同的方式继续遍历各个级别:要获得booklang属性,请使用$doc->book->title->attributes()->lang

$xml=simplexml_load_file("yourfile.xml");
echo $xml->book[0]['category'];

PHP provides a SimpleXML class in the standard library that can be used for parsing XML files. PHP在标准库中提供了SimpleXML类,该类可用于解析XML文件。

$data = <<<END
  <bookstore>
  <book category="cooking">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
</bookstore>
END;


$xml = simplexml_load_string($data); 
$categoryAttributes = $xml->xpath('/bookstore/book/@category');
echo $categoryAttributes[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM