【问题标题】:read xml file attributes读取xml文件属性
【发布时间】:2016-07-12 09:18:51
【问题描述】:

我正在尝试从 url 读取 rss 提要,我成功获得了标题、描述等。
现在我在阅读属性信息时遇到了问题。
我的xml是这样的:

<item>
<guid>https://www.edx.org/node/22726</guid>
<title>Managing Projects with Microsoft Project</title>
<link>
 https://www.edx.org/course/managing-projects-microsoft-project-microsoft-cld213x
</link>
<description>
 Want to master project management? Have a project to manage but unsure where to begin? With over 20 million users, Microsoft Project is the go to app for project managers. 
</description>
<pubDate>Wed, 06 Jul 2016 16:21:40 -0400</pubDate>
<course:id>course-v1:Microsoft+CLD213x+2T2016</course:id>
<course:code>CLD213x</course:code>
<course:created>Thu, 16 Jun 2016 14:59:55 -0400</course:created>
<course:start>2016-07-11 00:00:00</course:start>
<course:end>2016-12-31 00:00:00</course:end>
<course:self_paced>0</course:self_paced>
<course:length>6 modules</course:length>
<course:prerequisites>
 Basic project management knowledge and skills Basic knowledge and skills using any current Windows® operating system (preferably Windows 10) Competency in using other Microsoft® Office® applications (preferably Office 2016)
</course:prerequisites>
</item> 

我可以轻松访问标题、描述、发布日期等,但在访问&lt;course:length&gt; &lt;course:id&gt; &lt;course:image-banner&gt; etc 时遇到问题

我的php代码是

<?php
 $rss = simplexml_load_file('https://www.example.org/api/v2/report/course-feed/rss');
echo '<h1>'. $rss->channel->title . '</h1>';
foreach ($rss->channel->item as $item) {
 echo '<h2><a href="'. $item->link .'">' . $item->title . "</a></h2>";
 echo "<p>" . $item->pubDate . "</p>";
 echo "<p>" . $item->description . "</p>";

} ?>

【问题讨论】:

    标签: php xml


    【解决方案1】:

    这是一个命名空间问题!首先,您的文档必须具有xmlns:course="//URL" 属性。然后你可以像这样访问你的&lt;course:*&gt;

    $rss = simplexml_load_file('https://www.example.org/api/v2/report/course-feed/rss');
    $namespaces = $rss->getNamespaces(true);//Add this line
    echo '<h1>'. $rss->channel->title . '</h1>';
    foreach ($rss->channel->item as $item) {
         echo '<h2><a href="'. $item->link .'">' . $item->title . "</a></h2>";
         echo "<p>" . $item->pubDate . "</p>";
         echo "<p>" . $item->description . "</p>";
    
         $course = $item->children($namespaces['course']);
         echo $course->id;
         echo $course->prerequisites;
    }
    

    【讨论】:

    • 我正在添加这个答案 :) 迟到了 30 秒 +1
    • @ChetanAmeta 80% 的时间都发生在我身上:D
    猜你喜欢
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多