如何从 PHP 中的 SimpleXMLObject 解析值“@attribute”

How to parse value `@attribute` from a SimpleXMLObject in PHP

我正在尝试解析 starkoverflow.com/feeds/tag/{$tagName}。 这是我的代码:

<?php
    $xml = file_get_contents("http://whosebug.com/feeds/tag/php");
    $simpleXml = simplexml_load_string($xml);
    $attr = $simpleXml->entry->category->@attributes;

?>

当我执行上面的代码时出现错误,Parse error: syntax error, unexpected '@', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in D:\wamp\www\success\protoT.php on line 4

所以,我的问题是如何获取 @attributes?

的数组 Scrrenshot

您使用appropriately documented method: attributes()

$attr = $simpleXml->entry->category->attributes();

除了$simpleXml->entry->category是一个数组,所以需要指定要访问数组中的哪一项:

$attr = $simpleXml->entry->category[0]->attributes();

编辑

除非像我刚刚了解到的那样,您只需要引用第一个元素

关键是,实现没有spoon数组。

获取所有属性为数组,可以使用attributes()方法:

$all_attributes = $simpleXml->entry->category->attributes();

然而,大多数时候,您真正想要的是一个特定的属性,在这种情况下您只需使用数组键表示法:

$id_attribute = $simpleXml->entry->category['id'];

注意这个returns一个对象;传递它时,您通常希望只使用表示其值的字符串:

$id_value = (string)$simpleXml->entry->category['id'];

以上假设你总是想要 first <entry> 中的 first <category> 元素,甚至如果有多个。它实际上是指定第 0 项的简写(即使每个元素只有一个也有效):

$id_value = (string)$simpleXml->entry[0]->category[0]['id'];

或者,当然,遍历每个集合(同样,有一个或多个并不重要,foreach 仍然有效):

foreach ( $simpleXml->entry as $entry ) {
    foreach ( $entry->category as $category ) {
        $id_value_for_this_category = (string)$category['id'];
    }
}