使用 PHP5 按名称解析 XML 属性


Parsing XML Attributes by name with PHP5

尝试在PHP中解析XML文档时,不会返回任何内容。

我尝试使用的 XML 文档:

http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml

我尝试过的代码:

$player = simplexml_load_file('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
foreach ($player->PlayerName as $playerInfo) {
     echo $playerInfo['firstName'];
}

我也尝试过:

$player = simplexml_load_file('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
echo "Name: " . $player->PlayerName[0]['firstName'];

我需要更改哪些内容才能显示属性?

您可以尝试自己print_r整个数据,并最终找到所需的内容:

var_dump($player->Player->PlayerName->Attrib['value']->__toString())
//⇒ string(7) "Daniele"

要列出所有"值"(名字,姓氏,...),您需要列出所有子项及其属性:

$xml = simplexml_load_file('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
 foreach ($xml as $player) {
    foreach ($player->PlayerName->children() as $attrib) {
        echo $attrib['name'] . ': ' . $attrib['value'] . PHP_EOL; 
    }
 }

输出:

名字:丹尼尔姓氏: 中提琴通用名称:维奥拉·解说名称:

这不起作用,因为您尝试访问的是属性而不是节点值。

您可能还会遇到问题,因为 xml 对于简单 xml 不"有效"。请参阅我的博客文章,了解使用 php 解析 xml 的问题,请点击此处 http://dracoblue.net/dev/gotchas-when-parsing-xml-html-with-php/

如果您改用我的 Craur (https://github.com/DracoBlue/Craur) 库,它将如下所示:

$xml_string = file_get_contents('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
$craur = Craur::createFromXml($xml_string);
echo $craur->get('Player.PlayerName.Attrib@value'); // works since the first attrib entry is the name

如果要确定属性(或选择另一个属性),请使用:

$xml_string = file_get_contents('http://cdn.content.easports.com/media2011/fifa11zoneplayer/25068538/632A0001_10_ZONE_PLAYER_iUa.xml');
$craur = Craur::createFromXml($xml_string);
foreach ($craur->get('Player.PlayerName.Attrib[]') as $attribute)
{
    if ($attribute->get('@name') == 'firstName')
    {
        echo $attribute->get('@value');
    }
}