如何通过给定的父ID将XML子节点存储在PHP变量中?

<account VGS0035="VGS0035">

        <realm>Smolderweb</realm>

        <realmint>smolderweb-us</realmint>

        <type>PvP</type>

        <race>Undead</race>

        <gender>Male</gender>

        <class>Mage</class>

        <faction>Horde</faction>

        <level>60</level>

        <description>(60% mount, green/blue gear)</description>

        <price>210</price>

        <stock>1</stock>

        <id>VGS0035</id>

        <screenshot>https://vanilla.games/wp-content/uploads/2019/08/wow-classic-mage.jpg</screenshot>

    </account>


    <account VGS0036="VGS0036">

        <realm>Faerlina</realm>

        <realmint>faerlina-us</realmint>

        <type>PvP</type>

        <race>Undead</race>

        <gender>Male</gender>

        <class>Mage</class>

        <faction>Horde</faction>

        <level>60</level>

        <description>(100% mount, epic/blue gear, Tailoring 300, First Aid 225, MC+ONY+BWL attuned, 150 gold)</description>

        <price>400</price>

        <stock>1</stock>

        <id>VGS0036</id>

        <screenshot>https://i.imgur.com/cdeAdwe.jpg</screenshot>

    </account>


    <account VGS0037="VGS0037">

        <realm>Faerlina</realm>

        <realmint>faerlina-us</realmint>

        <type>PvP</type>

        <race>Undead</race>

        <gender>Male</gender>

        <class>Mage</class>

        <faction>Horde</faction>

        <level>60</level>

        <description>(60% mount, green/blue/epic gear, 100 gold)</description>

        <price>250</price>

        <stock>1</stock>

        <id>VGS0037</id>

        <screenshot>https://vanilla.games/wp-content/uploads/2019/08/wow-classic-mage.jpg</screenshot>

    </account>

我将以下内容封装在 XML 标签中。我有一个 PHP 页面,我在其中传递变量 page?id=VGS0003 - 我想提取 PHP 变量中该节点的所有子元素以供使用。


Example: 


$realm = $account->realm;

$region = $account-region;

$race = $account->race;

我几乎尝试了所有方法,但似乎没有任何效果。无论我是否在循环中放置 if 语句,Foreach 都只返回最后一个节点。


慕码人2483693
浏览 71回答 1
1回答

慕森王

一种选择是使用 xpath"//account[id='$id']"和您要查找的 id。$elements = simplexml_load_string($xmlstr);$id = "VGS0037";$query = "//account[id='$id']";$account = $elements->xpath($query);$accountRace = $account[0]->race;echo $accountRace;输出Undead
打开App,查看更多内容
随时随地看视频慕课网APP