我可以使用php包含xml文件中的元素吗?
我有一个列表,包括寻找像这样的链接:我可以使用php包含xml文件中的元素吗?
<a href=index.php?p=page_1>Page 1</a>
<a href=index.php?p=page_2>Page 2</a>
<a href=index.php?p=page_3>Page 3</a>
当点击它们包括网页(page_1.inc.php或page_2.inc.php或page_3.inc.php)我的网页上感谢对此脚本:
<?php
$pages_dir = 'pages';
if(!empty($_GET['p'])){
$pages = scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php', $pages)){
include ($pages_dir.'/'.$p.'.inc.php');
}
else {
echo 'Sorry, could not find the page!';
}
}
else {
include($pages_dir.'/home.inc.php');
}
?>
期间。
我也有一个XML文件看起来像这样:
<program>
<item>
<date>27/8</date>
<title>Page 1</title>
<info>This is info text</info>
</item>
<item>
<date>3/9</date>
<title>Page 2</title>
<info>This is info text again</info>
</item>
<item>
<date>10/9</date>
<title>Page 3</title>
<info>This just some info</info>
</item>
</program>
这就是我想要达到的目标:
如果我点击链接“1”,它会显示在“这是信息文本”上这一页。
如果我点击“页面2”链接,它会在页面上显示“这是信息文本”。
如果我点击链接“第3页”,它会在页面上显示“This just some info”。
我清楚了吗? 有没有解决方法?
您应该可以使用xpath()方法与SimpleXMLElement一起执行此操作。
$xmlString = file_get_contents("path/to/xml/file.xml");
$xml = new SimpleXMLElement($xmlString);
$info = $xml->xpath("/program/item[title='Page " . $page . "']/info");
echo (string) $info[0];
更新:
要获得所有日期的数组,你会做这样的事情:
$xmlString = file_get_contents("path/to/xml/file.xml");
$xml = new SimpleXMLElement($xmlString);
$results = $xml->xpath("/program/item/date");
$dates = array();
if (!empty($results)) {
foreach ($results as $date) {
array_push($dates, (string) $date); // It's important to typecast from SimpleXMLElement to string here
}
}
此外,您还可以结合逻辑,如果需要的话,从第一和第二个例子。您可以重复使用$xml
对象进行多个XPath查询。
如果您需要$dates
是唯一的,你可以做array_push()
前添加一个in_array()
检查,也可以在foreach后使用array_unique()
。
好的...因为我是PHP新手,想要学习它,不只是使用它,让我们看看我是否理解! 两个第一行用SimpleXMLElement函数读取xml文件的内容,对吧? 第三行设置$ info,将元素“info”作为“item”的字符串读取,并显示$ page。 最后一行打印$ info。 我对不对? – lindhe
@ Lindhe94无后顾之忧。我曾经是PHP新手。是的,前两行是正确的。第三行是使用XPath(我建议你阅读它)来扫描'$ xml'变量中包含的XML。该xpath查询正在过滤到我们关心的XML节点。它从'program'开始,然后转到所有'item',然后限制'item'返回具有节点'title'的文本“Page 1”,“Page 2”等。最后,它选择这个上下文中的info信息节点。 'info'节点中的文本作为数组返回到'$ info',我们只选择第一个索引(只有一个结果)。 –
噢,另外一个问题就是...... 当我把这个插入到我的代码中时,我会在上面的代码中创建一个elseif语句来指定它将被打印的时间。 我需要做一些类似于if语句的事情。我可以以某种方式制作所有日期的数组并使用in_array函数吗?如果是这样的话:我该如何创建这个数组? – lindhe
是的,这是可能的。有一个简单的解决方案。如果没有人很快发帖,我会回到这个。 – cwallenpoole