仅显示基于xml类别的特定产品

时间:2013-11-29 15:35:03

标签: php xml xml-parsing

我正在加载.xml文件并将其转换为我的需求。到目前为止,一切都很好。 在这个xml中有一个主产品类别和子类别,而且这个xml还有各种产品,例如:儿童服装等等。

是否有可能只获得特定子类别的结果?

这是我的代码:

<?php header('Content-Type: text/xml'); ?>
<?php
echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"; 
?>

<?
// specify url of xml file
$url = "xml_feeds.xml";
$xml = simplexml_load_file($url);

echo '<PRODUCTS>';
// loop begins
foreach($xml->PRODUCT as $PRODUCT)
{

$input = $PRODUCT->CATEGORY_NAME;
list($a, $b) = explode(' » ', $input); //i am split the CATEGORY_NAME coz contains and the sub category.

$my_title = $PRODUCT->NAME;
$title = trim($my_title);
$description = $PRODUCT->DESCRIPTION;
$mastercat = $a;
$subcat = $b;
$manufacturer = $PRODUCT->MANUFACTURER;
$price = $PRODUCT->PRICE_WITH_VAT;
$url = $PRODUCT->PRODUCT_URL;
$imageurl = $PRODUCT->IMAGE_URL;

echo '
<PRODUCT>
<ID><![CDATA['.$PRODUCT->ID.']]></ID>
<NAME><![CDATA['.$my_title.']]></NAME>
<DESCRIPTION><![CDATA['.$description.']]></DESCRIPTION>
<CATEGORY_NAME><![CDATA['.$mastercat.']]></CATEGORY_NAME>
<SUB_CATEGORY_NAME><![CDATA['.$subcat.']]></SUB_CATEGORY_NAME>
<MANUFACTURER><![CDATA['.$manufacturer.']]></MANUFACTURER>
<PREVIOUS_PRICE_WITH_VAT><![CDATA['.$price.']]></PREVIOUS_PRICE_WITH_VAT>
<PRICE_WITH_VAT><![CDATA['.$price.']]></PRICE_WITH_VAT>
<PRODUCT_URL><![CDATA['.$url.']]></PRODUCT_URL>
<IMAGE_URL><![CDATA['.$imageurl.']]></IMAGE_URL>
<THUMBNAIL_URL><![CDATA[]]></THUMBNAIL_URL>
</PRODUCT>';

}
// loop ends

echo '</PRODUCTS>';
?>

1 个答案:

答案 0 :(得分:0)

我解决了,

在回复xml我之前:

if ($b == "The Sub Cat to Display"){

echo '
<PRODUCT>
<ID><![CDATA['.$PRODUCT->ID.']]></ID>
<NAME><![CDATA['.$my_title.']]></NAME>
<DESCRIPTION><![CDATA['.$description.']]></DESCRIPTION>
<CATEGORY_NAME><![CDATA['.$mastercat.']]></CATEGORY_NAME>
<SUB_CATEGORY_NAME><![CDATA['.$subcat.']]></SUB_CATEGORY_NAME>
<MANUFACTURER><![CDATA['.$manufacturer.']]></MANUFACTURER>
<PREVIOUS_PRICE_WITH_VAT><![CDATA['.$price.']]></PREVIOUS_PRICE_WITH_VAT>
<PRICE_WITH_VAT><![CDATA['.$price.']]></PRICE_WITH_VAT>
<PRODUCT_URL><![CDATA['.$url.']]></PRODUCT_URL>
<IMAGE_URL><![CDATA['.$imageurl.']]></IMAGE_URL>
<THUMBNAIL_URL><![CDATA[]]></THUMBNAIL_URL>
</PRODUCT>';


}