
本文详解如何利用 php 的 xmlwriter 类,将过滤后的 rss 数据数组转换为符合规范的 xml 文档,重点解决元素嵌套错误、数组访问误用及编码格式等常见问题,并提供可直接运行的完整示例代码。
本文详解如何利用 php 的 xmlwriter 类,将过滤后的 rss 数据数组转换为符合规范的 xml 文档,重点解决元素嵌套错误、数组访问误用及编码格式等常见问题,并提供可直接运行的完整示例代码。
在 PHP 中,将关联数组动态生成标准 XML(如用于选举结果 Feed)是一项高频需求,但初学者常因混淆 SimpleXML 对象与原生数组、忽略 XML 元素命名规则或遗漏编码设置而失败。核心问题在于:$electionresults 是通过 array() 构造的普通 PHP 数组,而非 SimpleXML 对象——因此必须使用 $race['title'] 而非 $race->title 访问键值;同时,startElement() 的参数必须是字符串字面量(如 'title'),而非未加引号的变量名(如 name)。
以下是修正后的完整、健壮的实现方案:
<?php $races = [
"Governor",
"1st District Representative in Congress",
"37th District State Senator",
"107th District Representative in State Legislature",
"108th District Representative in State Legislature",
"109th District Representative in State Legislature",
"110th District Representative in State Legislature"
];
function has_keywords($haystack, $wordlist): bool {
if (!is_string($haystack)) return false;
foreach ($wordlist as $w) {
if (stripos($haystack, $w) !== false) {
return true;
}
}
return false;
}
// 安全加载 RSS(添加错误处理)
$rss_url = "https://mielections.us/election/results/RSS/2022PRI_MI_CENR_SUMMARY.rss";
$rss = simplexml_load_file($rss_url);
if ($rss === false) {
die("Failed to load RSS feed from: $rss_url");
}
$electionresults = [];
foreach ($rss->channel->item as $i) {
$title = (string)$i->title;
$desc = (string)$i->description;
$category = (string)$i->category;
if (
has_keywords($title, $races) ||
has_keywords($desc, $races) ||
has_keywords($category, $races)
) {
$electionresults[] = [
'title' => $title,
'description' => $desc,
'link' => (string)$i->link
];
}
}
// 使用 XMLWriter 构建 XML
$xml = new XMLWriter();
$xml->openURI('election-results.xml');
$xml->setIndent(true);
$xml->setIndentString(' ');
$xml->startDocument('1.0', 'UTF-8');
$xml->startElement('election');
foreach ($electionresults as $race) {
$xml->startElement('race');
$xml->startElement('title'); // 注意:字符串字面量,加引号
$xml->text($race['title']); // 关联数组访问,非对象属性
$xml->endElement();
$xml->startElement('data'); // 建议语义化命名,如 'description'
$xml->text($race['description']);
$xml->endElement();
$xml->endElement();
}
$xml->endElement();
$xml->endDocument();
$xml->flush();
unset($xml);
echo "✅ XML feed generated successfully: election-results.xml\n";
?>
关键修正与最佳实践说明:
- ✅ 严格区分数据类型:
$electionresults是数组 → 使用$race['title'];若误写为$race->title或$race['title'][0](原答案中冗余索引)将导致 Notice 或空值。 - ✅ 元素名必须为字符串:
$xml->startElement('title'),不可省略引号(name是未定义常量,会触发警告)。 - ✅ 强制类型转换:对 SimpleXML 元素统一
(string)强转,避免对象残留引发__toString()意外行为。 - ✅ 增强健壮性:添加 RSS 加载失败检查、
has_keywords输入校验、UTF-8 显式声明。 - ⚠️ 注意事项:确保运行环境启用
xmlwriter扩展(PHP 默认开启);输出文件路径需有写入权限;若需 HTTP 输出,请改用php://output并设置header('Content-Type: application/xml')。
此方案生成的 XML 符合 W3C 标准,可直接被 Feed 阅读器、前端 AJAX 或其他后端服务消费,是构建动态数据 Feed 的可靠范式。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











