PHP | SimpleXMLElement attributes()函数
先决条件:阅读 XML 基础知识
SimpleXMLElement::attributes()函数是PHP中的一个内置函数,用于从 SimpleXML 对象的 XML 标记中检索属性及其值。
句法:
SimpleXMLElement SimpleXMLElement::attributes( $namespace, $is_prefix )
参数:该函数接受上面提到的两个参数,如下所述:
- $namespace:它是可选参数。它指定检索到的属性的命名空间。
- $is_prefix:布尔参数。如果 $namespace 是前缀,则为 True,如果 $namespace 为 URI,则为 False。其默认值为 False。
返回值:它返回一个 SimpleXMLElement 对象,该对象可以迭代 SimpleXMLElement 对象的标签的属性。如果 SimpleXMLElement 对象已经是属性而不是标记,则返回 null。
注意:此函数在PHP 5.0.1 及更新版本上可用。
下面的程序说明了PHP中的 SimpleXMLElement::attributes()函数:
方案一:
php
Geeks123
GeeksforGeeks
+91-XXXXXXXXXX
Noida, UP, India
XML;
// Loading string as simple xml object
$xml = simplexml_load_string($user);
// Print children attribute with its value
foreach($xml->address[0]->attributes() as $key => $value)
{
echo $key . " => " . $value . "";
}
?>
php
Geeks123
GeeksforGeeks
+91-XXXXXXXXXX
Noida, UP, India
XML;
// Loading string as simple xml object
$xml = simplexml_load_string($user);
// Print children attribute
foreach($xml->children() as $child) {
echo "Child name: " . $child->getName()
. " =>" . $child . "
";
foreach($child->attributes() as $key => $value)
echo " parameter: "
. $key . " => " . $value . "";
}
?>
输出:
font-color => blue
font => awesome-fonts
font-size => 24px
方案二:
PHP
Geeks123
GeeksforGeeks
+91-XXXXXXXXXX
Noida, UP, India
XML;
// Loading string as simple xml object
$xml = simplexml_load_string($user);
// Print children attribute
foreach($xml->children() as $child) {
echo "Child name: " . $child->getName()
. " =>" . $child . "
";
foreach($child->attributes() as $key => $value)
echo " parameter: "
. $key . " => " . $value . "";
}
?>
输出:
Child name: username => Geeks123
parameter: font-color => green
parameter: font => awesome-fonts
parameter: font-size => 72px
Child name: name => GeeksforGeeks
parameter: font-color => blue
parameter: font => awesome-fonts
parameter: font-size => 36px
Child name: phone => +91-XXXXXXXXXX
parameter: font-color => blue
parameter: type => number
parameter: font => awesome-fonts
parameter: font-size => 24px
Child name: address => Noida, UP, India
parameter: font-color => blue
parameter: font => awesome-fonts
parameter: font-size => 24px
参考: https://www. PHP.net/manual/en/simplexmlelement.attributes。 PHP