【发布时间】:2011-07-22 09:50:46
【问题描述】:
<li id="weather" class="widget-container widget-dark-blue">
<h3 class="widget-title">Weather</h3>
<?php include (TEMPLATEPATH . '/widgets/weather.php'); ?>
</li>
weather.php 向天气服务发出 curl 请求并返回一个表格。通过 DomDocument 类,我读取了 td's 中的值。我将当前天气状况的类名应用于div.weather。
<?php
require_once('classes/SmartDOMDocument.class.php');
$url = 'some/domain...';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
$str = curl_exec($curl);
$dom = new SmartDOMDocument();
$dom->loadHTML($str);
$xpath = new DOMXPath($dom);
$tds = $xpath->query('//div/table/tr/td');
foreach ($tds as $key => $cell) {
if ($key==1) {
$condition = $cell->textContent;
//$cell->parentNode->setAttribute('class', 'hello');
echo "<div class='weather " . strtolower($condition) ."'>";
...
?>
一切正常。我唯一的问题是,是否有一种 PHP 方法可以将类名 $condition 应用于保存信息的列表项? 因此,我不想在我的 li#weather 中有一个带有 $condtion 的类,我希望有一个 li#weather 类。
<li id="weather" class="widget-container widget-dark-blue $condition">
有什么方法可以将 $condition 类应用于包含所有内容的列表。我可以很容易地用 javascript/jquery 做到这一点。但是我想知道是否有一些服务器端解决方案。
谢谢
【问题讨论】:
-
您可以使用
$node->parentNode获取节点的父节点。如果包含<li>是直接祖先,那么像$cell->parentNode->setAttribute(...)这样的东西可以解决问题。 -
正如您在我上面的代码中看到的那样,它应该是直接祖先,对。两者之间没有任何东西。但是例如
$cell->parentNode->setAttribute('class', 'hello');不起作用。可能是因为 $cell 实际上是原始 curl-request 的td,而不是包含此 curl-request 的列表的子级。
标签: php domdocument classname