我有一个个人网站,我希望展示我已经制作的一些下载内容。每个下载都有一个说明和下载链接,但我不想为每个项目创建一个单独的页面(例如' item1.php',' item2.php',因为格式非常符合标准。"因此,我将所有文本放在XML文件中,然后使用PHP来解析它。
这是我的XML的样子:
<txtdb>
<txt name="index">
<str key="title">Index</key>
<str key="metadescription">Personal site</key>
<str key="navigation">Navigation</key>
<str key="description"><!CDATA[[<h2>Description</h2>]]></key>
<str key="download"><!CDATA[[<h2>Download</h2>]]></key>
</txt>
<txt name="item1">
<str key="title">Item 1</key>
<str key="metadescription">Item 1 is awesome, get it now!</key>
<str key="description"><!CDATA[[<p>Item 1 is an incredible item that you must get right away!</p>]]></key>
<str key="download"><!CDATA[[<a href="http://dropbox.com">Here</a>]]></key>
</txt>
<!-- ... -->
</txtdb>
这是我的index.php:
<?php
$current = 'index';
class TextDatabase()
{
private $_xdb;
private $_name;
public function __construct($xdt)
{
$this->_xdb = simplexml_load_file('./incl/txt.xml');
$this->_name = $xdt;
}
public function getString($key, $name = null)
{
if (empty($name))
{
$name = $this->_name;
}
$str = $this->_xdb->xpath(sprintf("//txt[@name='%s']/str[@key='%s']", $name, $key));
return empty($str[0]) ? null : (string) html_entity_decode($str[0]);
}
}
session_start();
if (isSet($_GET['name']))
{
$current = $_GET['name'];
$_SESSION['name'] = $current;
}
else if (isSet($_SESSION['name']))
{
$current = $_SESSION['name'];
}
else
{
$current = 'index';
}
$TxtDb = new TextDatabase($current);
include_once('incl/header.php');
include_once('incl/sidebar.left.php');
if ($current == 'index'):?>
<h2><?php echo $TxtDb->getString('navigation'); ?></h2>
<ul>
<li><a href="index.php?name=item1"><?php echo $TxtDb->getString('title','item1'); ?></a></li>
<li><a href="index.php?name=item2"><?php echo $TxtDb->getString('title','item2'); ?></a></li>
<!-- more items -->
</ul>
<?php else: ?>
<h2><?php echo $TxtDb->getString('description','index'); ?></h2>
<article><?php echo $TxtDb->getString('description'); ?></article>
<h2><?php echo $TxtDb->getString('download','index'); ?></h2>
<article><?php echo $TxtDb->getString('download'); ?></article>
<?php endif;
include_once('incl/sidebar.right.php');
include_once('incl/footer.php');
?>
目前,它有效。如果我去'index.php&#39;我看到了我的物品清单。然后,当我点击其中一个时,我发送到&#39; index.php?name = item n 。&#39;但是,我在标题中有一个链接指向&#39; index.php&#39;当我点击它时,页面重新加载,但我没有回到索引。为了返回索引,我必须将链接更改为指向&quot; index.php?name = index&#39;,但我不喜欢这样。有没有办法制作&#34; index.php&#34; (没有参数)返回索引而不是当前项(我相信它存储在PHP会话中)?
这是我第一次使用PHP(我更喜欢C#),很抱歉,如果这是一个愚蠢的问题。谢谢你的帮助。
答案 0 :(得分:0)
我认为这个问题导致了有关您的架构的多个子问题。例如,为什么要在会话中存储name参数?这样做的意义通常是在多个请求之间传输数据,而不必每次都提交它。
据我所知,如果不作为参数提交,您希望 name 不存在。另一方面,您的代码通过实现从会话中获取缺少参数的回退来捕获这种情况。
因此我建议像这样更改index.php:
...
session_start();
if (isSet($_GET['name']))
{
$current = $_GET['name'];
}
else
{
$current = 'index';
}
...
顺便说一下。 unset($_SESSION['name'])
可能会从会话中删除项目变得很方便,但我建议重新考虑index.php逻辑,而不是在根本不需要会话存储时使其更复杂。 ; - )