控制RSS风格

时间:2012-05-29 16:02:44

标签: php rss

目前我正在使用此代码从Yahoo Weather中提取RSS源,但我想按照我想要的方式设置它,但我不知道如何。

<?php
    $doc = new DOMDocument();
    $doc->load('http://xml.weather.yahoo.com/forecastrss/10013_f.xml');
    $channel = $doc->getElementsByTagName("channel");
    foreach($channel as $chnl)
    {
    $item = $chnl->getElementsByTagName("item");
    foreach($item as $itemgotten)
    {
    $describe = $itemgotten->getElementsByTagName("description");
    $description = $describe->item(0)->nodeValue;
    echo $description;
    }
    }
    ?>

2 个答案:

答案 0 :(得分:0)

正如你所说的@Michael,一旦你改变了这样的代码:

$doc = new DOMDocument();
$doc->load('http://xml.weather.yahoo.com/forecastrss/10013_f.xml');
$channel = $doc->getElementsByTagName("channel");
foreach($channel as $chnl){
    $item = $chnl->getElementsByTagName("item");
    foreach($item as $itemgotten) {
        $describe = $itemgotten->getElementsByTagName("description");
        $description = $describe->item(0)->nodeValue;
        echo "<div class='description'>" . htmlspecialchars($description) . "</description>";
    }
}

您必须创建必要的CSS以根据需要显示信息。

答案 1 :(得分:0)

有两个选项:

选项1

与上一个答案不同的方法:如果您查看实际的XML文件,那么您还会看到相同的描述也包含在各个标记中:

<yweather:condition  text="Fair"  code="34"  temp="84"  date="Tue, 29 May 2012 6:49 pm EDT" />
<yweather:forecast day="Tue" date="29 May 2012" low="70" high="86" text="Partly Cloudy" code="30" />
<yweather:forecast day="Wed" date="30 May 2012" low="64" high="85" text="Scattered Thunderstorms" code="38" />
<yweather:forecast day="Thu" date="31 May 2012" low="56" high="75" text="Partly Cloudy" code="30" />
<yweather:forecast day="Fri" date="1 Jun 2012" low="63" high="69" text="Partly Cloudy" code="30" />
<yweather:forecast day="Sat" date="2 Jun 2012" low="59" high="70" text="Showers" code="11" />

没有理由不能单独查询所有这些数据并将其全部包装在您想要的任何HTML标签中

要从conditions属性获取属性,这可以起作用:

<?php
$doc = new DOMDocument(); 
$doc->load('http://xml.weather.yahoo.com/forecastrss/10013_f.xml'); 
$channel = $doc->getElementsByTagName("channel"); 
foreach($channel as $chnl){ 
  $item = $chnl->getElementsByTagName("item"); 
  foreach($item as $itemgotten) { 
    $nodes = $itemgotten->getElementsByTagName('condition')->item(0);
    if ($nodes->hasAttributes()) {
      foreach ($nodes->attributes as $attr) {
        $name = $attr->nodeName;
        $value = $attr->nodeValue;
        echo "Attribute '$name' :: '$value'<br />";
      }
    }
  }
}
?>

选项2

如果您确实选择了上一个答案中建议的方法,请不要忘记您只能使用描述中使用的HTML标记(除非您在PHP中进行各种字符串操作),但您仍然可以使用/通过在CSS中使用级联样式来设置这些标记的样式:

div.description { /*general div styles*/ }
div.description b { /*styles for anything within a b tag in the description div*/ }
...

......等等