0

目前我正在使用此代码从雅虎天气中提取 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;
    }
    }
    ?>
4

2 回答 2

0

有2个选项:

选项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*/ }
...

...等等

于 2012-05-29T16:18:30.053 回答
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 以根据需要显示信息。

于 2012-05-29T16:13:35.353 回答