使用php解析xml命名空间

时间:2011-05-11 15:28:53

标签: php xml simplexml xml-namespaces

我一直在尝试从Google日历中提取此XML文件中的数据,而对命名空间的内容却没有太大成功。

这只是我遇到问题的gdgCal数据 - 我搜索了所有内容并且无法让它工作:(

任何帮助表示赞赏! :)

<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gCal='http://schemas.google.com/gCal/2005' xmlns:gd='http://schemas.google.com/g/2005'>
<id>http://www.google.com/calendar/feeds/abc%40group.calendar.google.com/private-abc/full/abc</id>
<published>2011-05-03T07:45:56.000Z</published>
<updated>2011-05-03T07:45:56.000Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'/>
<title type='text'>title</title>
<content type='text'>content</content>
<link rel='alternate' type='text/html' href='http://www.google.com/calendar/event?eid=abc' title='alternate'/>
<link rel='self' type='application/atom+xml' href='http://www.google.com/calendar/feeds/abc%40group.calendar.google.com/private-abc/full/abc'/>
<author>
<name>my@email.com</name>
<email>my@email.com</email>
</author>
<gd:comments>
<gd:feedLink href='http://www.google.com/calendar/feeds/abc%40group.calendar.google.com/private-abc/full/abc/comments'/>
</gd:comments>
<gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'/>
<gd:where/>
<gd:who email='abc@group.calendar.google.com' rel='http://schemas.google.com/g/2005#event.organizer' valueString='TV2'/>
<gd:when endTime='2011-05-10T22:50:00.000+01:00' startTime='2011-05-10T22:25:00.000+01:00'/>
<gd:transparency value='http://schemas.google.com/g/2005#event.opaque'/>
<gCal:anyoneCanAddSelf value='false'/>
<gCal:guestsCanInviteOthers value='true'/>
<gCal:guestsCanModify value='false'/>
<gCal:guestsCanSeeGuests value='true'/>
<gCal:sequence value='0'/>
<gCal:uid value='abc@google.com'/>
</entry>

到目前为止,PHP代码是:

<?php
$source = "data2.xml";
$xmlstr = file_get_contents($source);
$parseXMLFile = new SimpleXMLElement($xmlstr);
echo $parseXMLFile->id[0];
echo "<br>";
echo $parseXMLFile->title[0];
echo "<br>";
echo $parseXMLFile->content[0];
?>

1 个答案:

答案 0 :(得分:1)

查看此答案: https://stackoverflow.com/a/622363/195835

基本上它建议使用xPath调用,例如

$xml = new SimpleXMLElement($r);

foreach($xml->xpath('//event:event') as $event) {
    var_export($event->xpath('event:sessionKey'));
}