The string I am trying to split is $item['category_names']
which for example contains Hair, Fashion, News
I currently have the following code:
$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories = "<category>" . $cat . "</category>\n";
}
I want the outcome of $categories
to be like the following so I can echo it out later somewhere.
<category>Hair</category>\n
<category>Fashion</category>\n
<category>News</category>\n
Not sure if I am going the right way about this?
In your code you are overwritting the $categories variable in each iteration. The correct code would look like:
$categories = '';
$cats = explode(",", $item['category_names']);
foreach($cats as $cat) {
$cat = trim($cat);
$categories .= "<category>" . $cat . "</category>\n";
}
update: as @Nanne suggested, explode only on ','
Without a for loop
$item['category_names'] = "Hair, Fashion, News";
$categories = "<category>".
implode("</category>\n<category>",
array_map('trim', explode(",", $item['category_names']))) .
"</category>\n";
echo $categories;
if you use this:
$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories = "<category>" . $cat . "</category>\n";
}
the $categories string is overwritten each time, so "hair" and "fasion" are lost..
if you however add a dot before the equal sign in the for loop, like so:
$cats = explode(", ", $item['category_names']);
foreach($cats as $cat) {
$categories .= "<category>" . $cat . "</category>\n";
}
the $catergories string will consist of all three values :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With