PHP 使用 PHP 简单 XML 从 XML 获取数据

PHP get data form XML using PHPSimpleXML

我正在尝试从 xml 文件中获取数据,但遇到了问题,因为 table 的级别比我能找到的示例要多一些。

我希望能够遍历 <Event> 的每个实例,因为 <Information><Events> 仅打开和关闭数据。 <Event> 根据记录的事件数重复。

table 结构的示例是:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Information>
    <Events>
        <Event>
            <Time>3141.29</Time>
            <PrimaryObject ID="487">
                <Name>Player1</Name>
                <Country>us</Country>
            </PrimaryObject>
            <Action>Move</Action>
            <SecondaryObject ID="814">
                <Name>Dog</Name>
                <Parent>487</Parent>
            </SecondaryObject>
        </Event>
    </Events>
</Information>

PHP代码是:

<!DOCTYPE html>
<html>
<body>

<?php
$xml=simplexml_load_file("data.xml") or die("Error: Cannot create object");
foreach($xml->Event as $events) {
    $id = $events->PrimaryObject->attributes();
    $name = $events->PrimaryObject->Name;
    ...
    echo $id['ID'].' '. $name;
    echo "<br>";
  }
?>

</body>
</html>

我不确定您要查找的到底是什么数据,但这里有所有内容,使用 xpath,您可以挑选:

$events = $xml->xpath('.//Event');
foreach($events as $event) {        
    $dat = $event->xpath('./PrimaryObject')[0];
    $time= $event->xpath('./Time');    
    $id = $dat->xpath('./@ID');
    $name = $dat->xpath('./Name');
    $country = $dat->xpath('./Country');
    
    $dat2 = $event->xpath('./SecondaryObject')[0];
    $action= $event->xpath('./Action');    
    $id2 = $dat2->xpath('./@ID');
    $name2 = $dat2->xpath('./Name');
    $parent = $dat2->xpath('./Parent');    
            
    echo 'Time: ' . $time[0];
    echo "<br>"; 
    echo 'Action: ' . $action[0];
    echo "<br>";    
    echo "<br>"; 
    echo 'Primary Object Data:';
    echo "<br>";    
    echo 'ID: ' . $id[0];
    echo "<br>";
    echo 'Name: ' . $name[0];
    echo "<br>";
    echo 'Country: ' . $country[0];
    echo "<br>";
    echo "<br>";   
    echo "<br>";
    echo 'Secondary Object Data:';
    echo "<br>";    
    echo 'ID: ' . $id2[0];
    echo "<br>";
    echo 'Name: ' . $name2[0];
    echo "<br>";
    echo 'Parent: ' . $parent[0];
    echo "<br>";         
  }

输出:

Time: 3141.29
Action: Move

Primary Object Data:
ID: 487
Name: Player1
Country: us


Secondary Object Data:
ID: 814
Name: Dog
Parent: 487

您必须使用 事件

$xml->Events->Event as $events

例如

$xml=simplexml_load_file("data.xml") or die("Error: Cannot create object");

foreach($xml->Events->Event as $events) {
    $id = $events->PrimaryObject->attributes();
    $name = $events->PrimaryObject->Name;
    echo $id['ID'].' '. $name;
    echo "<br>";
}

输出

487 Player1

Php demo