解析谷歌日历XML Feed

时间:2009-08-28 13:38:08

标签: php xml simplexml

我从公共谷歌日历中获取XML Feed。看起来像这样:

<?xml version='1.0' encoding='UTF-8'?>
    <feed xmlns='................' xmlns:gd='http://schemas.google.com/g/2005'>
        <id>http://www.google.com/calendar/feeds/........./public/full</id>
        <updated>2009-08-24T10:57:00.000Z</updated>
        <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'/>
            <title type='text'>Sports Events</title>
    .....
        <entry>
            <id>...........</id>
            <published>2009-08-14T00:29:58.000Z</published>
            <updated>2009-08-14T00:29:58.000Z</updated>
            <category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/g/2005#event'/>
..............
            <georss:where>
                <gml:Point>
                    <gml:pos>11.111111 -22.22222</gml:pos>
                </gml:Point>
            </georss:where>
            <gd:eventStatus value='http://schemas.google.com/g/2005#event.confirmed'/>
            <gd:transparency value='http://schemas.google.com/g/2005#event.transparent'/>
            <gCal:uid value='.........@google.com'/>
            <gCal:sequence value='0'/>
            <gd:when startTime='2009-10-03' endTime='2009-10-04'/>

.............

现在到PHP:

$calendar = simplexml_load_file('http://my.feed.com');
foreach ($calendar->entry as $item) {
    //here I get the whole <entry> node
    $gd = $item->children('http://schemas.google.com/g/2005');
    // now in $gd I have all nodes like <gd:XXXXX>
}

问题是如何从这里获得价值?

<gml:pos>11.111111 -22.22222</gml:pos>

它不存在于我的$ gd变量中,如何获取此节点?

4 个答案:

答案 0 :(得分:10)

我强烈建议您使用此库:https://github.com/collegeman/coreylib。它会让所有事情从始至终都变得令人难以置信。

答案 1 :(得分:5)

当然有几种方法可以解析XML。 Display Google Calendar events on your PHP Web site with XPath(请参阅“使用PHP解析Google日历Feed”)和Integrate your PHP application with Google Calendar是两个包含示例代码等的综合资源。

就个人而言,我使用了以下方法:

$doc = new DOMDocument(); 
$doc->load('http://my.feed.com');
$entries = $doc->getElementsByTagName("entry"); 
foreach ( $entries as $entry ) { 
  $titles = $entry->getElementsByTagName("title"); 
  $title = $titles->item(0)->nodeValue;

  $times = $entry->getElementsByTagName("when"); 
  $startTime = $times->item(0)->getAttributeNode("startTime")->value;
  $when = date("l jS \o\f F Y - h:i A", strtotime($startTime));
  // ...
}

为了访问georss命名空间等,请查看(及其输出)

foreach ($doc->getElementsByTagNameNS('*', '*') as $element) {
  echo 'localName: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}

答案 2 :(得分:1)

您可以使用Zend GData库来解析Google Web服务(包括日历)。它比尝试手动使用XML代码更容易。有一个教程可以向您展示如何执行此操作here

答案 3 :(得分:0)

完整日历比Coreylib更容易。虽然我确信它非常强大,但Coreylib并不简单。

我在5分钟内运行了FullCalendar。 http://arshaw.com/fullcalendar/docs/google_calendar/