如何使用 SimpleXML 获取标签中的属性

How to get attribute in tag using SimpleXML

我不确定如何称呼我想要的,所以如果你能提供更准确的术语,我会更新我的问题。

我想从结构如下的 XML 网站获取数据:

<body>
    <predictions>
        <message text="message"/>
    </predictions>
    <predictions>
        <direction title="Dir1">
            <prediction epochTime="1521560640000" seconds="724" minutes="12" isDeparture="true" affectedByLayover="true" dirTag="paciland" vehicle="1606" block="22"/>
        </direction>
    </predictions>
</body>

我想获取秒(或分钟...)值。

我找到了有关从如下结构中获取数据的信息:

<body>
    <predictions>
        <message text="message"/>
    </predictions>
    <predictions>
        <direction title="Dir1">
            <prediction>
                epochTime="1521560640000"
                seconds="724" 
                minutes="12" 
                isDeparture="true" 
                affectedByLayover="true" 
                dirTag="paciland" 
                vehicle="1606" 
                block="22"
            </prediction>
        </direction>
    </predictions>
</body>

标签中没有数据。

我从未使用过 SimpleXML 所以我对如何获得它有点困惑。

可以使用 $element['attribute_name'].

使用 simpleXML 访问属性

这是从 <prediction> 标签中获取 seconds 属性的示例。

$xml = '<body>
    <predictions>
        <message text="message"/>
    </predictions>
    <predictions>
        <direction title="Dir1">
            <prediction epochTime="1521560640000" seconds="724" minutes="12" isDeparture="true" affectedByLayover="true" dirTag="paciland" vehicle="1606" block="22"/>
        </direction>
    </predictions>
</body>';

$xmlobj = simplexml_load_string($xml);
foreach ($xmlobj->predictions as $prediction) {
    if (isset($prediction->direction)) {
        echo $prediction->direction->prediction['minutes'];
        echo $prediction->direction->prediction['seconds'];
    }
}