PHP XMLReader::getAttribute() 函式



定義和用法

XML 是一種標記語言,用於在網路上共享資料,XML 可供人和機器讀取。XMLReader 擴充套件用於讀取/檢索 XML 文件的內容,即使用 XMLReader 類的 方法,可以讀取 XML 文件的每個節點。

XMLReader::getAttribute() 函式是 XMLReader 類的一個函式,它接受一個表示屬性名稱的字串值,並返回其值。

語法

XMLReader::getAttribute($name);

引數

序號 引數及描述
1

name(必填)

這是一個表示屬性名稱的字串值。

返回值

此函式返回一個表示指定屬性值的字串值。如果指定屬性不存在,則此函式返回 NULL。

PHP 版本

此函式首次在 PHP 5 版本中引入,並在所有後續版本中均有效。

示例

以下示例演示了 XMLReader::getAttribute() 函式的用法:

data.xml
<Employee>
   <Name id = "name">Krishna</Name>
   <Age id = "age">22</Age>
   <City id = "city">Hyderabad</City>   
   <Phone id = "phone">980000000</Phone>   
</Employee>
sample.php
<?php
//Creating an XMLReader
$reader = new XMLReader();

//Opening a reader
$reader->open("data.xml");

//Reading the contents of the XML file
while($reader->read()){
   if ($reader->nodeType == XMLREADER::ELEMENT) { 
      $res = $reader->getAttribute('id'); 
      print($res."\n");
   }
}
//Closing the reader
$reader->close();
?>

這將產生以下結果:

name
age
city
phone

示例

以下是此函式的另一個示例:

test.xml
<data> 
   <name att = "test_attribute">Raju</name> 
   <age>32</age> 
   <phone>9848022338</phone> 
	<city>Hyderabad</city>
</data> 

sample.php

<?php
   //Creating an XMLReader
   $reader = new XMLReader();

   //Opening a reader
   $reader->open("test.xml");

   //Reading the contents
   $reader->next();
   $reader->read();
   $reader->next();
   print($reader->getAttribute("att")."\n");

   //Closing the reader
   $reader->close();
?>

這將產生以下結果:

test_attribute

示例

<?php
   //Creating an XMLReader
   $reader = new XMLReader();

   $data = "<data> 
      <name att = 'test_attribute'>Raju</name> 
      <age>32</age> 
      <phone>9848022338</phone> 
      <city>Hyderabad</city>
   </data> ";

   //Opening a reader
   $reader->xml($data);

   //Reading the contents
   $reader->next();
   $reader->read();
   $reader->next();
   print($reader->getAttribute("att")."\n");

   //Closing the reader
   $reader->close();
?>

這將產生以下結果:

test_attribute
php_function_reference.htm
廣告