php 8.6读取rss扩展字段时,可先解析为simplexmlelement,再将固定命名空间uri注册为自己的xpath前缀。真正需要匹配的是uri,源站更换前缀名称不应让查询失效。下面针对rss 2.0加dublin core扩展,需要simplexml与libxml。

PHP手册中的simplexml_load_string
读取有界的本地XML
示例使用已保存的本地文件,不让用户提供任意远程URL。限制体积并拒绝DOCTYPE,不启用外部实体替换;解析失败和没有文章分别处理。
$raw=file_get_contents('/srv/app/feed.xml');
if ($raw===false || strlen($raw)>2097152 || stripos($raw,')!==false) {
throw new RuntimeException('Rejected RSS');
}
$old=libxml_use_internal_errors(true);
try {
$rss=simplexml_load_string($raw,SimpleXMLElement::class,LIBXML_NONET);
if ($rss===false) throw new RuntimeException('Malformed RSS');
} finally { libxml_clear_errors();libxml_use_internal_errors($old); }

PHP手册中的SimpleXMLElement::registerXPathNamespace
注册查询前缀并提取作者
$items=$rss->xpath('/rss/channel/item');
if ($items===false) throw new RuntimeException('XPath failed');
$result=[];
foreach ($items as $item) {
$item->registerXPathNamespace('d','http://purl.org/dc/elements/1.1/');
$authors=$item->xpath('d:creator');
if ($authors===false) throw new RuntimeException('Author query failed');
$result[]=['title'=>(string)$item->title,
'author'=>isset($authors[0])?(string)$authors[0]:null];
}
检查实际格式和输出
Atom的feed、entry位于另一命名空间,需注册相应URI并改用带前缀路径,不能直接套RSS路径。作者不存在时返回null,空结果不等于解析失败。输出到HTML时转义标题和作者,订阅源内容不是可信HTML。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










