好的,所以我试图创建一个基于PHP的购物车,从目录的XML文件中读取。唯一的问题是,当我将信息打印到我的网站上时,它会打印出XML文件中的所有内容。我需要将它们分类(即鞋子、服装等),只打印出所谓的类别。
XML文件的结构是这样的(为组织目的添加的额外空间):
<items>
<product>
<id> TSHIRT01 </id>
<title> Red T-Shirt </title>
<category> apparel </category>
<description> T-Shirt designed by Sassafrass </description>
<img> ../images/apparel1.jpg </img>
<price> 5.99 </price>
</product>
</items>
我使用以下代码将信息打印到我的网站上:
<?php echo render_products_from_xml(); ?>
下面是这个PHP命令的函数,它只设置了输出到网站本身的结构:
function render_products_from_xml(){
$counter=0;
$output = '<table class="products"> <tr>';
foreach(get_xml_catalog() as $product)
{
$counter++;
$output .='
<td>
<div class="title">
<h2> '.$product->title.' </h2>
</div>
<div class="cells">
<img src="'.$product->img.'" height="220" width="170" />
</div>
<div class="description">
<span>
'.$product->description.'
</span>
</div>
<div class="price">
$'.$product->price.'
</div>
<div class="addToCart">
<a href="addToCart.php?id='.$product->id.'">Add To Cart</a>
</div>
</td>';
if($counter%4 == 0)
{
$output .='<tr>';
}
}
$output .='</tr></table>';
return $output;}
我希望PHP函数最终看起来像这样(所有大写的更改):
<?php echo render_products_from_xml($CATEGORY=='APPAREL'); ?>
或者类似的东西:
<?php echo render_APPAREL_products_from_xml(); ?>
我只需要一些关于如何添加一些函数来帮助对从XML文件中读取的信息进行分类的提示。此外,我不想为每个类别创建新的XML文件,因为我需要复制所有代码,以便从单独的XML文件中提取信息,并将所有产品整合到一个购物车中。我正在寻找更容易管理的东西。
最后,我有很多后台功能在后台工作,只是获取信息并设置实际的购物车本身,所以如果你觉得需要我给你更多的代码,那就去问吧!此外,如果我对任何事情含糊其辞,请毫不犹豫地告诉我,这样我就可以(希望)纠正问题或回答你的问题。
提前感谢你所能提供的一切帮助!我真的很感激。:)
您的代码没有显示函数get_xml_catalog()
,它显然是在获取XML。
因此,使用您给出的代码,您可以对函数render_products_from_xml()
:进行相对较小的更改
function render_products_from_xml($category) {
$counter=0;
$output = '<table class="products"> <tr>';
foreach (get_xml_catalog() as $product) {
if ((string)$product->category == $category || $category == '') {
$counter++;
$output .= 'all that stuff';
if ($counter % 4 == 0) $output .= '<tr>';
} // if
} // foreach
$output .='</tr></table>';
return $output;
}
评论:
(1) 现在通过传递参数$category
:来调用该函数
echo render_products_from_xml('apparel');
(2) 在foreach
循环中,只有类别为==$category
的<product>
被添加到$output
。
(3) 如果$category
是空字符串,则每个<product>
都被添加到$output
。
替代方案:
更改函数get_xml_catalog($category)
以在该位置进行选择。使用xpath
可能会做得最好。