PHP SimpleXMLElement::attributes() 函式



定義和用法

XML 是一種標記語言,用於在網路上共享資料,XML 既可供人類閱讀,也可供機器閱讀。SimpleXMLElement 類在 PHP 中表示 XML 文件。

SimpleXMLElement::attributes() 函式查詢 SimpleXMLElement 物件中的屬性及其值,並返回它們。

語法

SimpleXMLElement::attributes([$namespace, $is_prefix]);

引數

序號 引數和描述
1

namespace(可選)

這是一個字串值,表示屬性所屬的名稱空間。

2

is_prefix(可選)

這是一個布林值,表示指定的名稱空間是字首 (TRUE) 還是 URL (FALSE)。

返回值

此函式返回一個包含屬性的 SimpleXMLElement 類物件,如果在屬性上呼叫則返回 FALSE。

PHP 版本

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

示例

以下示例演示了 SimpleXMLIterator::attributes() 函式的用法。

<html>
   <head>
      <body>
         <?php
            $str="<?xml version='1.0' standalone='yes'?>
            <Tutorial>
               <Name type = 'programming'>JavaFX</Name>
               <Pages>535</Pages>
               <Author>Krishna</Author>
               <Version>11</Version>
            </Tutorial>";
            $xml = new SimpleXMLElement($str);
            $attr = $xml->Name->attributes();
            print_r($attr); 
         ?>      
      </body>
   </head>   
</html>

這將產生以下結果:

SimpleXMLElement Object ( [@attributes] => Array ( [type] => programming ) )

示例

假設我們有一個包含以下標籤的 xml 檔案:

Data.xml

<Tutorials>

</Tutorials>

在下面的示例中,我們添加了一個帶有屬性的子元素,並使用 attributes() 函式檢索它:

<html>
   <head>      
      <body>         
         <?php
            $doc = new DOMDocument;
            $xml = simplexml_load_file("data.xml");
            
            //file to SimpleXMLElement 
            $simpleXmlElement = simplexml_import_dom($xml);
            
            //Adding the child node
            $child = $xml->addChild('Tutorial');
            $ele = $child->addChild('Name', 'OpenCV');
            $ele->addAttribute('type', 'Image Processing');			
            $child->addChild('Pages', '230');
            $child->addChild('Author', 'Maruthi');
            $child->addChild('Version', '5.5');
            $xml->asXML("output.xml");   
            $attr = $xml->Tutorial->Name->attributes();
            print_r($attr); 			
         ?>
      </body>
   </head>
</html>

這將產生以下結果:

SimpleXMLElement Object ( [@attributes] => Array ( [type] => Image Processing ) )
php_function_reference.htm
廣告