使用PHP获取XML属性

时间:2011-04-04 05:01:01

标签: php xml

嘿伙计们,我四处寻找帮助,但没有发现任何遗憾。我试图使用PHP来获取XML文件的内容并从属性中提取数据。我已经检查过其他教程但尝试过但都没有用。

这是XML文件:

<eveapi version="2">
  <currentTime>2011-04-03 03:55:59</currentTime>
  <result>
    <rowset name="notifications" key="notificationID" columns="notificationID,typeID,senderID,sentDate,read">
      <row notificationID="339040500" typeID="75" senderID="1000137" sentDate="2011-04-03 03:53:00" read="0" />
    </rowset>
  </result>
  <cachedUntil>2011-04-03 04:25:59</cachedUntil>
</eveapi>

我正试图从'typeID'&amp; 'sentDate'。此外,此XML文件可能包含多个标记。

欢迎所有帮助,谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用以下代码: -

$xmlstr = '<eveapi version="2">
  <currentTime>2011-04-03 03:55:59</currentTime>
  <result>
    <rowset name="notifications" key="notificationID" columns="notificationID,typeID,senderID,sentDate,read">
      <row notificationID="339040500" typeID="75" senderID="1000137" sentDate="2011-04-03 03:53:00" read="0" />

    </rowset>
  </result>
  <cachedUntil>2011-04-03 04:25:59</cachedUntil>
</eveapi>
';


$xml = simplexml_load_string($xmlstr);

print_r ($xml->result->rowset->row['typeID']);

注意:如果rowset中有多行,则在object中,该行将作为数组的集合。在这种情况下,你必须像bellow一样访问typeID -

print_r ($xml->result->rowset->row[0]['typeID']);

答案 1 :(得分:1)

穿上阻燃服......

$string = '<eveapi version="2">
  <currentTime>2011-04-03 03:55:59</currentTime>
  <result>
    <rowset name="notifications" key="notificationID" columns="notificationID,typeID,senderID,sentDate,read">
      <row notificationID="339040500" typeID="75" senderID="1000137" sentDate="2011-04-03 03:53:00" read="0" />
    </rowset>
  </result>
  <cachedUntil>2011-04-03 04:25:59</cachedUntil>
</eveapi>';

preg_match_all('#([\S]+)="(.*?)"#is', $string, $matches);
unset($matches[0]);

$xml = array_combine($matches[1], $matches[2]);

print_r($xml);

=

Array
(
    [version] => 2
    [name] => notifications
    [key] => notificationID
    [columns] => notificationID,typeID,senderID,sentDate,read
    [notificationID] => 339040500
    [typeID] => 75
    [senderID] => 1000137
    [sentDate] => 2011-04-03 03:53:00
    [read] => 0
)