我使用此代码创建一个xml文件,该文件列出了目录中文件的URL和描述。但我需要在这个xml中添加一些文件。所以我想给文件一个数字(或ID),比如1为文件2 .... n,像每行的计数器我怎么能这样做?
谢谢
<?php
$myfeed = new RSSFeed();
// Open the current directory (or specify it)
$dir = opendir ("./");
while (false !== ($file = readdir($dir))) {
if (strpos($file, '.jpg',1)||strpos($file, '.gif',1) ) {
$myfeed->SetItem("http://host.com/images/$file", "$file", "");
}
}
// Output the XML File
$fp = fopen('rss.xml', 'w');
fwrite($fp, $myfeed->output());
fclose($fp);
echo $myfeed->output(); //lets see that
class RSSFeed {
// VARIABLES
// channel vars
var $channel_url;
var $channel_title;
// items
var $items = array();
var $nritems;
// FUNCTIONS
// constructor
function RSSFeed() {
$this->nritems=0;
$this->channel_url='';
$this->channel_title='';
}
// set channel vars
function SetChannel($url, $title, $description, $lang, $copyright, $creator, $subject) {
$this->channel_url=$url;
$this->channel_title=$title;
}
// set item
function SetItem($url, $title, $description) {
$this->items[$this->nritems]['url']=$url;
$this->items[$this->nritems]['title']=$title;
$this->nritems++;
}
// output feed
function Output() {
$output = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$output .= '<playlist version="0" xmlns = "http://xspf.org/ns/0/">'."\n";
$output .= '<trackList>'."\n";
for($k=0; $k<$this->nritems; $k++) {
$output .= '<track>'."\n";
$output .= '<location>'.$this->items[$k]['url'].'</location>'."\n";
$output .= '<image></image>'."\n";
$output .= '<annotation>'.$this->items[$k]['title'].'</annotation>'."\n";
$output .= '</track>'."\n";
};
$output .= '</trackList>'."\n";
$output .= '</playlist>'."\n";
return $output;
}
};
?>
答案 0 :(得分:0)
首先,我不认为使用string
- 函数创建XML是一个好主意,而是使用像simplexml
或DOM
这样的解析器。
为每个条目分配id
,您可以在$k
中使用function Output()
:
for($k=0; $k<$this->nritems; $k++) {
$output .= '<track>'."\n";
$output .= "<id>$k</id>\n";
// (...)
$output .= "</track>\n";
}
或将id
作为属性添加到<track>
- 节点:
$output .= "<track id=\"$k\">\n";