【发布时间】:2013-05-18 21:21:38
【问题描述】:
我有一个单独的.php 页面,我想在其中加载单个帖子。
为此,我的 index.php 中有一些链接可以加载 single.php 页面:
<a href="single.php?blog_no=12">Post 12</a>
<a href="single.php?blog_no=11">Post 11</a>
<a href="single.php?blog_no=10">Post 10</a>
我在我的 single.php 页面的 url 中获取变量,我想在 xml 文件中找到(并显示)与此变量对应的元素:
<?php
if(isset($_GET["blog_no"])) {
$i = $_GET["blog_no"];
$elements = new SimpleXMLElement('data.xml', null, true);
$query = $elements->xpath(" /elements/element[@id='$i'] ");
foreach($query as $element) {
echo $elements->element['size'];
echo $elements->element['category'];
echo $elements->element->title;
}
?>
这是我的 xml 文件的示例:
<elements>
<element id="12" size="square" category="portfolio">
<tag tag="printer printing 3d apple iphone 5 bumper case"></tag>
<icon class="icon-picture"></icon>
<urlpage url="/contact/contact.html"></urlpage>
<urlimage src='./Post thumbnail images/01.png'></urlimage>
<date date="8 Apr"></date>
<title>Minimal Bumper for iPhone 5 : Protect your iphone with a lightwheight and protect full case </title>
</element>
<element id="11" size="normal" category="portfolio">
<tag tag="printer printing 3d apple iphone 5 case slim"></tag>
<icon class="icon-picture"></icon>
<urlpage url="/portfolio/11.html"></urlpage>
<urlimage src='./Post thumbnail images/tape-dribbble.jpg'></urlimage>
<date date="21 Jan"></date>
<title>UltraSlim case</title>
</element>
</elements>
但没有任何效果。
【问题讨论】:
-
“但没有任何效果。” 不是有效的问题描述。在您在这里提出问题之前,请确保您已启用错误记录和报告并将其设置为最高级别,然后跟踪所有通知、警告和错误并首先修复它们。这将为您省去很多问号,因为 PHP 会告诉您问题出在哪里 - 就像您在此处的示例代码中没有执行正确的 xpath。
-
在您最后一次编辑之后,您的代码甚至可以立即使用 (eval.in/30703)。那么你的问题是什么?
-
这段代码当然没有任何错误,但它不能正常工作。它总是得到第一个 xml 节点...
-
这是因为原始代码在
foreach循环中访问原始文档的方式,而不是 xpath 查询的结果。原始代码中的问题不仅仅是变量替换。 -
不,它得到的是您要求的节点。
foreach也将其放入$element,但您需要使用该变量进行输出。如果你不这样做,那么你就没有。见eval.in/private/ed061ca92bcd48