【发布时间】:2021-12-19 09:32:34
【问题描述】:
我正在尝试使用 PHP 解析带有命名空间的 XML 文档以输出 HTML,并保留其原始结构。
我在下面的代码中使用了 XPATH 和 foreach 循环来呈现标题、段落和列表,但这不尊重文档的原始结构。我也不清楚如何呈现嵌入在 XML 标记中的内容中的 URL 之类的东西。
XML 示例:
<a:section>
<c:ref value="1">1</c:ref>
<c:title>Title of content</c:title>
<f:subsection>
<c:ref value="1.1">1.1</c:ref>
<c:title>Subsection title</c:title>
<b:content>Make sure you check out this link: <c:url address="www.google.com" type="https">google.com</c:url> and then review the list below:</b:content>
<c:list type="bullet">
<c:listitem>
<b:content>bullet item 1</b:content>
</c:listitem>
<c:listitem>
<b:content>bullet item 2</b:content>
</c:listitem>
<c:listitem>
<b:content>bullet item 3</b:content>
</c:listitem>
</c:list>
<b:content>More content here in text form</b:content>
</f:subsection>
</a:section>
PHP 示例:
$xml = file_get_contents('content.xml');
$sxml = new SimpleXmlElement($xml);
$section = $sxml->xpath('//a:section');
foreach ($section as $s) {
$sectionnumber = $s->xpath('c:ref');
$title = $s->xpath('c:title');
foreach ($title as $t) {
echo '<h2>'.$sectionnumber[0].' '.$t.'</h2>';
}
}
$subsection = $s->xpath('f:subsection');
foreach ($subsection as $ss) {
$subheadingnumber = $ss->xpath('c:ref');
$subheading = $ss->xpath('c:title');
foreach ($subheading as $sh) {
echo '<h3>'.$subheadingnumber[0].' '.$sh.'</h3>';
}
$paragraphs = $ss->xpath('b:content');
foreach ($paragraphs as $p){
echo '<p>'.$p.'</p>';
}
$lists = $ss->xpath('c:list');
foreach ($lists as $l){
$listitem = $l->xpath('c:listitem');
foreach ($listitem as $item){
$listcontent = $item->xpath('b:content');
foreach ($listcontent as $a){
echo '<li>'.$a.'</li>';
}
}
}
}
【问题讨论】:
-
您是否考虑过让 XSLT 完成 XML 到 HTML 转换的工作?毕竟,您需要做的就是编写一个 XSLT 样式表并转换例如
<xsl:template match="c:list"><ul><xsl:apply-templates/></ul></xsl:template>等等,例如<xsl:template match="c:listitem"><li><xsl:apply-templates/></li></xsl:template>和文档结构将被保留,只是映射到 HTML。 -
谢谢@MartinHonnen。对于以前没有真正使用过 XML 的人来说非常有用。采用 XSLT 方法是我试图解决的问题的正确解决方案。
标签: php xml xpath namespaces