Jump to content

PHP/XML and deliminated text


andrew_php

Recommended Posts

Hello All!

 

Quick question, I have a table in MySQL I want to export as XML, which I have been able to fine with $xml_output, however I have one field which is semi-colon deliminated text that I would like to seperate into individual elements. eg.

 

table_x

 

*************************************************

* Name * Color                   *

*     *                       *

*************************************************

* Billy * Blue                 *

*************************************************

* Sally * Green;Blue                 *

*************************************************

* Pedro * Red;Green;Blue;Yellow          *

*************************************************

 

I would like the output to be:

 

<root>
<name>Billy</name>
  <favourite_colors> 
   <color>Blue</color>	
  </favourite_colors> 
<name>Sally</name>
  <favourite_colors> 
   <color>Green</color>	
   <color>Blue</color>	
  </favourite_colors> 
<name>Pedro</name>
  <favourite_colors> 
   <color>Red</color>	
   <color>Green</color>	
   <color>Blue</color>	
   <color>Yellow</color>	
  </favourite_colors> 
</root>

 

I am somewhat still a noob, so apologies in advance if I have not expressed this request as simply as possible.

 

Any help would be greatly appreciated.

 

Kind Regards,

Andrew

Link to comment
https://forums.phpfreaks.com/topic/111976-phpxml-and-deliminated-text/
Share on other sites

I don't use xml all that much, but I'd say when you have the color variable ready(with all the colors separated by ;), do a $temp = explode(";", $colors) and then step through each variable, printing a <color> tag for each. Remember to ignore the last one though, since it will be blank(since there's nothing on the right side of your last semicolon)

try

<?php
$data = array (
		array('Billy', 'Green'),
		array('Sally','Green;Blue'),
		array('Pedro' , 'Red;Green;Blue;Yellow')
		);

$str = "<root>\n";
foreach ($data as $person)
{
$str .= "<person>\n";
$str .= "<name>{$person[0]}</name>\n";
$str .= "<favorite_colors>\n";

$colors = explode(';', $person[1]);
foreach ($colors as $fc)
{
	$str .= "<color>$fc</color>\n";
}

$str .= "</favorite_colors>\n";
$str .= "</person>\n";
}
$str .= "</root>\n";

echo $str;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.