1

我正在使用该simplexml_load_file命令将数据从 api 解析到我订阅的 MMO,以制作获取当前公会公鸡的工具。从 api 返回的原始 xml 如下所示:

<apiresponse>
    <guild name="Seekers of Forgotten Pasts" world="Cannith" memberCount="1312">
        <characters>
            <character name="Nethershadow" surname="" rank_level="5" rank_name="Officer" race="Halfling" gender="m" alignment="True Neutral">
            <classes>
                <class name="Ranger" level="2"/>
                <class name="Rogue" level="8"/>
            </classes>
        </character>
        <character name="..." surname="..." rank_level="..." rank_name="..." race="..." gender="..." alignment="...">
            ...
        </character>
        <character name="Calomel" surname="" rank_level="10" rank_name="Member" race="Drow Elf" gender="m" alignment="Lawful Good">
            <classes>
                <class name="Paladin" level="5"/>
            </classes>
        </character>
    </guild>
<cache_info cached_until_gmt="2013-01-05 19:23"/>
</apiresponse>

现在,当我插入我的 php 以检索名称列表时,如下所示:

<?php
    $names = array();
    $xmlGuild = simplexml_load_file($DataDDO_api_urlFullGuildSearch);
    $characters = $xmlGuild->guild->characters->character;
    for ($i = 0; $i < sizeof($characters); $i++) {
        $names[] = $characters[$i]->attributes()->name;
    }
    echo "\n\nTotal members: " . count($names) . "\n\n<pre>\n";
    print_r($names);
    echo "</pre>\n";
?>

结果我得到:

Total members: 1312

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => Nethershadow
        )
    [...] => SimpleXMLElement Object
        (
            [0] => ...
        )
    [1311] => SimpleXMLElement Object
        (
            [0] => Calomel
        )
)

而不是我所期望的:

Array
(
    [0] => Nethershadow
    [...] => ...
    [1311] => Calomel
)

为什么是这样?

4

1 回答 1

1

如果您想要它们的文本值,您必须将 SimpleXML 对象转换为字符串。

<?php
    $names = array();
    $apiresponse = simplexml_load_file($DataDDO_api_urlFullGuildSearch);

    foreach ($apiresponse->guild->characters->character as $char) 
    {
        $names[] = (string)$char->attributes()->name;
    }

    echo "\n\nTotal members: " . count($names) . "\n\n<pre>\n";
    print_r($names);
    echo "</pre>\n";
?>
于 2013-01-05T16:19:57.480 回答