I am trying to print the different category's selected in a single line in xml, like
<cat_name>meeting, food and drinks, sports</cat_name>
The output I am getting:
<cat_name>meeting, food and drinks, sports,</cat_name>
I want to remove only the last comma.
The code I have written so far is:
$sq="
select category_main.cat_name
from category_main
join category
on(category.cat_id=category_main.cat_id)
where category.event_id='$event_id'
";
$e=mysql_query($sq);
$xml ='<cat_name>';
while($row=mysql_fetch_array($e))
{
$res=$row['cat_name'];
//$new = substr($val,0,-1);
$xml .="$res, ";
}
$xml .='</cat_name>';
echo $xml;
Call trim()
with the optional second parameter as a ','
trim($cat_name, ',')
However, since you're doing this in a while loop, you should build an array then implode()
it rather than building the string in the loop. This avoids the extra comma to begin with.
$arr = array();
while($row=mysql_fetch_array($e))
{
$arr[] = $row['cat_name'];
}
$cat_name = implode(",", $arr);
// $cat_name is now "meeting, food and drinks, sports"
You can do this by [i used my variable]
$str = substr($str,0, (strlen($str)-1));
Or use a rtrim, rtrim( $cat , ',' )
http://php.net/rtrim