使用PHP5按名称解析XML属性

时间:2014-11-27 15:47:04

标签: php xml

尝试在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'];

我需要更改要显示的属性?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

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

$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; 
    }

 }

输出:

firstName: Daniele
lastName: Viola
commonName: Viola D.
commentaryName:

答案 2 :(得分:-1)

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

您可能也会遇到问题,因为xml对于简单的xml来说不是“有效”。请参阅我的博客文章,了解使用php http://dracoblue.net/dev/gotchas-when-parsing-xml-html-with-php/

解析xml的问题

如果您使用我的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');
    }
}