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()函数:
程序1:
// Loading XML document to $user
$user = <<
Geeks123
GeeksforGeeks
+91-XXXXXXXXXX
font-size="24px">
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 . "";
}
?>
输出:
font-color => blue
font => awsome-fonts
font-size => 24px
程序2:
// Loading XML document to $user
$user = <<
font="awsome-fonts" font-size="72px">
Geeks123
font-size="36px">
GeeksforGeeks
font="awsome-fonts" font-size="24px">
+91-XXXXXXXXXX
font-size="24px">
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 => awsome-fonts
parameter: font-size => 72px
Child name: name => GeeksforGeeks
parameter: font-color => blue
parameter: font => awsome-fonts
parameter: font-size => 36px
Child name: phone => +91-XXXXXXXXXX
parameter: font-color => blue
parameter: type => number
parameter: font => awsome-fonts
parameter: font-size => 24px
Child name: address => Noida, UP, India
parameter: font-color => blue
parameter: font => awsome-fonts
parameter: font-size => 24px