根据 id 显示一个 XML 条目

发布于 2024-09-28 13:24:18 字数 893 浏览 0 评论 0原文

试图建立一个快速而肮脏的新闻系统。

有一个基本的 XML 文件。

<?xml version="1.0" encoding="ISO-8859-1"?>
<articles>
  <article id="1">
    <title>Article title 001</title>
    <short>Short text</short>
 <long>Long text</long>
  </article>
  <article id="2">
    <title>Article title 002</title>
    <short>Short text</short>
 <long>Long text</long>
  </article>
</articles>

我可以使用以下代码显示所有文章:

<?php

 $xmldoc = new DOMDocument();
 $xmldoc->load('test.xml');

 $xpathvar = new Domxpath($xmldoc);

 $queryResult = $xpathvar->query('//articles/article'); // works fine grabs all articles
 foreach($queryResult as $result){
   echo $result->textContent;
 }
?>

我只是不知道如何根据 ID 仅显示一篇文章。

任何帮助都会很棒。

谢谢 斯特凡

Trying to make a quick and dirty news system.

Have a basic XML file.

<?xml version="1.0" encoding="ISO-8859-1"?>
<articles>
  <article id="1">
    <title>Article title 001</title>
    <short>Short text</short>
 <long>Long text</long>
  </article>
  <article id="2">
    <title>Article title 002</title>
    <short>Short text</short>
 <long>Long text</long>
  </article>
</articles>

I can display all the articles with the following code:

<?php

 $xmldoc = new DOMDocument();
 $xmldoc->load('test.xml');

 $xpathvar = new Domxpath($xmldoc);

 $queryResult = $xpathvar->query('//articles/article'); // works fine grabs all articles
 foreach($queryResult as $result){
   echo $result->textContent;
 }
?>

I just can't work out how to show just one article based on ID.

Any help would be great.

Thanks
Stefan

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

落日海湾 2024-10-05 13:24:18
$id = 1;
$queryResult = $xpathvar->query(sprintf('//articles/article[@id="%s"]', $id));
$id = 1;
$queryResult = $xpathvar->query(sprintf('//articles/article[@id="%s"]', $id));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文