Link to home
Start Free TrialLog in
Avatar of ST3VO
ST3VOFlag for United Kingdom of Great Britain and Northern Ireland

asked on

PHP - CSV to XML

Hi all,

I need some code to convert some data from a CSV file to XML but in the following format attached.

Hope someone can help.

Thanks

ST3VO.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Please post a sample of the CSV and show us how you want the XML to look, thanks.
Avatar of ST3VO

ASKER

opps...sorry I never attached the structure sample.

Here it is below.




<?xml version="1.0" encoding="UTF-8"?>
<gallery xmlns:media="http://search.yahoo.com/mrss/">
	
	
	<settings>
		<mediaFolder type="large" media="video">video/</mediaFolder>
		<mediaFolder type="thumbnail" media="video">video/thumbs/</mediaFolder>
		<mediaFolder type="large" media="swf">video/</mediaFolder>
		<mediaFolder type="thumbnail" media="swf">video/thumbs/</mediaFolder>
		<mediaFolder type="large" media="image">images/</mediaFolder>
		<mediaFolder type="thumbnail" media="image">images/thumbs/</mediaFolder>
	</settings>	
 
<!--Data below 2 entries -->
<item url="website url" 
     Name="name data here"
    Surname="surname data here"
    Image="Image1 URL"
        <media:text>some text here</media:text>
        <media:content url="image1" type="image/jpeg" width="600" height="450" />
</item>
 
<item url="website url2" 
     Name="name 2 data here"
    Surname="surname 2 data here"
    Image="Image2 URL"
        <media:text>some text here</media:text>
        <media:content url="image2" type="image/jpeg" width="600" height="450" />
</item>
	
</gallery>

Open in new window

OK, I think I can help.  Can you show us the CSV so we can know how to get the fields from CSV into the right places in the XML?  Thanks, ~Ray
Avatar of ST3VO

ASKER

Great!!!

Here is a sample CSV attached!

Please let me know if you have any questions.

Cheers

st3vo

p.s: Couldn't attach csv ext's to upload so I renamed to .jpg, so please rename ext to .csv. thx!!!
test.jpg
Avatar of ST3VO

ASKER

Please feel free to modify the CSV if you wish to change the layout.
The XML created must be the same structure as the same though!

Hope you can help!

Thanks

st3vo
Can you please post that again as test.txt - my file associations are playing havoc with getting it opened so I can read it.  thanks, ~Ray
Avatar of ST3VO

ASKER

OK No probs!

Here it is attached!

Thanks!!!

Please let me know if you need anything else or have any further problems
test.txt
Avatar of ST3VO

ASKER

Hi Ray_Paseur did you get the .txt file and is it ok? Just wondering!

thx

st3vo
Yes, just had some other work intervening.  Will look at it this evening.
try this and tell me if it worked as you expect or not if not update me ....waiting your reply

<?php
        $file = file("test.txt");
        $fieldsep = ",";
echo count($file);
 
        for ($i=1;$i< count($file);$i++) {
                $line = explode($fieldsep, $file[$i]);
?>
<item url="<?= $line[0]?>"
     Name="<?= $line[1]?>"
    Surname="<?= $line[2]?>"
    Image="<?= $line[4]?>"
        <media:text><?= $line[5]?></media:text>
        <media:content url="<?= $line[6]?>" type="image/jpeg" width="600" height="450" />
</item>
 
<?
        }
?>

Open in new window


<?php // RAY_temp_csv_2_xml.php
// REFER TO MAN PAGE HERE: http://us.php.net/manual/en/function.fgetcsv.php
// BEWARE OF TWO FIELDS WITH THE SAME NAMES - SEE 'Image' - POSITION 4 OVERWRITES POSITION 3
// SOME TEST DATA PADDED WITH BLANKS
// csv= "url,          Name,             Surname,            Image, Image,      mediatext,        mediacontent \n";
$csv[]= "website url,  name data here,   surname data here,       , Image1 URL, some text here,   image1       \n";
$csv[]= "website url2, name 2 data here, surname 2 data here,     , Image2 URL, some text here 2, image2       \n";
 
 
// THE STATIC PART OF THE XML
$xml_head  = '<?xml version="1.0" encoding="UTF-8"?>
<gallery xmlns:media="http://search.yahoo.com/mrss/">
        <settings>
                <mediaFolder type="large" media="video">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="video">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="swf">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="swf">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="image">images/</mediaFolder>
                <mediaFolder type="thumbnail" media="image">images/thumbs/</mediaFolder>
        </settings>'. "\n";
 
$xml_tail = '</gallery>';
 
// THE XML WE ARE TRYING TO GENERATE
/* *************************
<!--Data below 2 entries -->
<item url="website url"
     Name="name data here"
    Surname="surname data here"
    Image="Image1 URL"
        <media:text>some text here</media:text>
        <media:content url="image1" type="image/jpeg" width="600" height="450" />
</item>
 
<item url="website url2"
     Name="name 2 data here"
    Surname="surname 2 data here"
    Image="Image2 URL"
        <media:text>some text here 2</media:text>
        <media:content url="image2" type="image/jpeg" width="600" height="450" />
</item>
*/ // **********************
 
// THE FIELDS OF THE CSV
$csv_fields = array(
   "url",
   "Name",
   "Surname",
   "Image",
   "Image",
   "media:text",
   "media:content"
 );
 
// USE OUTPUT BUFFERING SO WE CAN SEE THE XML AT THE END OF THE SCRIPT
ob_start();
 
// OUTPUT THE XML HEAD
echo $xml_head;
 
// IN THE "REAL WORLD" WE WOULD READ THE CSV FILE WITH fgtcsv() BUT HERE WE USE FOREACH + EXPLODE ON THE TEST DATA
foreach ($csv as $csvline)
{
   $csv_values = explode(',', $csvline);
 
// CHECK FOR MATCHING FIELD COUNTS
   if (count($csv_fields) != count($csv_values)) die("CSV FORMAT ERROR: $csvline");
 
// DO ANYTHING WE NEED TO TIDY UP THE VALUES
   foreach ($csv_values as $pointer => $csv_value)
   {
      $csv_values[$pointer] = trim($csv_value);
   }
 
// CREATE THE XML ITEMS
?>
<item <?=$csv_fields[0]?>="<?=$csv_values[0]?>"
      <?=$csv_fields[1]?>="<?=$csv_values[1]?>"
      <?=$csv_fields[2]?>="<?=$csv_values[2]?>"
      <?=$csv_fields[4]?>="<?=$csv_values[4]?>"
     <<?=$csv_fields[5]?>><?=$csv_values[5]?></<?=$csv_fields[5]?>>
     <<?=$csv_fields[6]?> url="<?=$csv_values[6]?>" type="image/jpeg" width="600" height="450" />
</item>
 
<?php
}
 
// RETRIEVE THE BUFFER
$xml_thing = ob_get_clean();
 
// AND SHOW THE BUFFER
echo "<pre>";
$xml_thing = htmlentities($xml_thing);
echo $xml_thing;

Open in new window

Add this after line 87
echo $xml_tail;

Open in new window

Avatar of ST3VO

ASKER

Hi Ray, I've tested your code but no xml is generated...any ideas why?
Avatar of ST3VO

ASKER

Hi Agamal,

Tested your code but I get the following error:

Parse error: syntax error, unexpected $end
Avatar of ST3VO

ASKER

Hi Agamal,

I changed your code to: (see attached)

and all I get is a 3 onscreen.
<?php
        $file = file("test.csv");
        $fieldsep = ",";
echo count($file);
 
        for ($i=1;$i< count($file);$i++) {
                $line = explode($fieldsep, $file[$i]);
		}
?>
<item url="<?= $line[0]?>"
     Name="<?= $line[1]?>"
    Surname="<?= $line[2]?>"
    Image="<?= $line[4]?>"
        <media:text><?= $line[5]?></media:text>
        <media:content url="<?= $line[6]?>" type="image/jpeg" width="600" height="450" />
</item>

Open in new window

Avatar of ST3VO

ASKER

Hi Ray,

I managed to sort the error I was getting.

I have a problem,...the feilds are not been populated.

This is the output I'm getting: (See below)

Thx

st3vo

<?xml version="1.0" encoding="UTF-8"?>
<gallery xmlns:media="http://search.yahoo.com/mrss/">
        <settings>
                <mediaFolder type="large" media="video">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="video">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="swf">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="swf">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="image">images/</mediaFolder>
                <mediaFolder type="thumbnail" media="image">images/thumbs/</mediaFolder>
        </settings>
<item <?=$csv_fields[0]?>="<?=$csv_values[0]?>"
      <?=$csv_fields[1]?>="<?=$csv_values[1]?>"
      <?=$csv_fields[2]?>="<?=$csv_values[2]?>"
      <?=$csv_fields[4]?>="<?=$csv_values[4]?>"
     <<?=$csv_fields[5]?>><?=$csv_values[5]?></<?=$csv_fields[5]?>>
     <<?=$csv_fields[6]?> url="<?=$csv_values[6]?>" type="image/jpeg" width="600" height="450" />
</item>
 
<item <?=$csv_fields[0]?>="<?=$csv_values[0]?>"
      <?=$csv_fields[1]?>="<?=$csv_values[1]?>"
      <?=$csv_fields[2]?>="<?=$csv_values[2]?>"
      <?=$csv_fields[4]?>="<?=$csv_values[4]?>"
     <<?=$csv_fields[5]?>><?=$csv_values[5]?></<?=$csv_fields[5]?>>
     <<?=$csv_fields[6]?> url="<?=$csv_values[6]?>" type="image/jpeg" width="600" height="450" />
</item>
 
</gallery>

Open in new window

sorry but i can't get what is the relation between your request and the last code you posted

the xml file output from my code will be in your web page source code we can force download so each time you run the script with CSV file you download the xml file
Avatar of ST3VO

ASKER

Hi agamal,

Yes if the file generate can be saved it would be great!

I just need it to work...

1. Load the csv data
2. Generate the code
3. Save it.
test this

<?php
header("Content-Transfer-Encoding: binary");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"file.xml\";" );
        $file = file("test.txt");
        $fieldsep = ",";
echo"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<gallery xmlns:media="http://search.yahoo.com/mrss/">
 
        <settings>
                <mediaFolder type="large" media="video">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="video">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="swf">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="swf">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="image">images/</mediaFolder>
                <mediaFolder type="thumbnail" media="image">images/thumbs/</mediaFolder>
        </settings>
 
<item url="website url"
     Name="name data here"
    Surname="surname data here"
    Image="Image1 URL"
        <media:text>some text here</media:text>
        <media:content url="image1" type="image/jpeg" width="600" height="450" />
</item>
 
<?
        for ($i=1;$i< count($file);$i++) {
                $line = explode($fieldsep, $file[$i]);
                $line[6] = str_replace("\n"," ",$line[6]);
?>
 
<item url="<?= $line[0]?>"
     Name="<?= $line[1]?>"
    Surname="<?= $line[2]?>"
    Image="<?= $line[4]?>"
        <media:text><?= $line[5]?></media:text>
        <media:content url="<?= $line[6]?>" type="image/jpeg" width="600" height="450" />
</item>
<?
        }
?>
 
</gallery>

Open in new window

Avatar of ST3VO

ASKER

hmmm....it's doing the stuff but please see the output generated below:

Here:

If you see below it's not inserting to content of the csv/txt file into the fields, it's just showing the php code but not the results.

For example: <?= $line[0]?> should be the data from the csv file.

<item url="<?= $line[0]?>"
     Name="<?= $line[1]?>"
    Surname="<?= $line[2]?>"
    Image="<?= $line[4]?>"
        <media:text><?= $line[5]?></media:text>
        <media:content url="<?= $line[6]?>" type="image/jpeg" width="600" height="450" />
</item>

Note: The test.txt is actually a csv file so for testing you need to rename test.txt to test.csv.

Hope it helps.

thx

st3vo

<?xml version="1.0" encoding="UTF-8"?>
<gallery xmlns:media="http://search.yahoo.com/mrss/">
 
        <settings>
                <mediaFolder type="large" media="video">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="video">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="swf">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="swf">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="image">images/</mediaFolder>
                <mediaFolder type="thumbnail" media="image">images/thumbs/</mediaFolder>
        </settings>
 
<item url="website url"
     Name="name data here"
    Surname="surname data here"
    Image="Image1 URL"
        <media:text>some text here</media:text>
        <media:content url="image1" type="image/jpeg" width="600" height="450" />
</item>
 
<?
        for ($i=1;$i< count($file);$i++) {
                $line = explode($fieldsep, $file[$i]);
                $line[6] = str_replace("\n"," ",$line[6]);
?>
 
<item url="<?= $line[0]?>"
     Name="<?= $line[1]?>"
    Surname="<?= $line[2]?>"
    Image="<?= $line[4]?>"
        <media:text><?= $line[5]?></media:text>
        <media:content url="<?= $line[6]?>" type="image/jpeg" width="600" height="450" />
</item>
<?
        }
?>
 
</gallery>
 

Open in new window

sorry again ... i can't get it ... you have a csv file and you are willing to import its data in xml file with format ...

 posted you a code and you are saying it is working

it force download of the file

and it worked with me ... very successfully ....

now you are saying it is not working and you get the code in you xml file ... if you are facing problem post the csv file and php code used to generate this faulted xml file ....because i don't understand how is my code worked and how you still reciving this defective xml ...
Try turning on PHP short tags.
Avatar of ST3VO

ASKER

Hi agamal,

What I am trying to say is that:

<item url="<?= $line[0]?>" should come out as <item url="website url" but it's generating a xml file in which all is ok but the above issue.

apart from that all is ok.

Here is the csv file with a sample data for the code to read.

test.txt needs to be renamed to test.csv

File attached.

Hope it helps to clarify if not please let me know.

thx again...


test.txt
Avatar of ST3VO

ASKER

Hmmm.....I think Ray_Paseur might be on to the problem.

Instead of turn on short tags how would the code below be written in long tags?

<?=$line[0]?>

thx
ASKER CERTIFIED SOLUTION
Avatar of agamal
agamal
Flag of United Arab Emirates image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
<?=$line[0]?>


is the same as

<?php echo $line[0] ?>

Avatar of ST3VO

ASKER

Thanks a million!!! :o)
Avatar of ST3VO

ASKER

Also, thanks for the tip Ray!!!!
@ST3VO: Going forward, you might consider giving points to more than one Expert.  I posted a complete, tested, working solution and the ONLY thing you needed to add on your end was the PHP short tags.  It seems odd that you completely ignored my solution when you accepted the answers. ~Ray
Avatar of ST3VO

ASKER

Hi Ray, I didn't ignore your solution...it's just that at the time I tested it, it didn't work for me so I tried the next solution.
I have already assigned the points and don't really know if that can be changed. :o(

No need to change them - I have lots of points.  Like I said, it's just a thought for going forward.  Best, ~Ray
Avatar of ST3VO

ASKER

Thanks Ray!
On the short tags (enabled by default in the standard PHP installation):
http://us.php.net/manual/en/ini.core.php#ini.short-open-tag

It can be enabled in a script.

Over and out, ~Ray

ini_set('short_open_tag', TRUE);

Open in new window

Avatar of ST3VO

ASKER

wow!!! Thanks a million for that!!!!
Avatar of ST3VO

ASKER

Any idea why I get 4 "

e.g: ""somedata"" instead of "somedata"  ?
where did you get somedata error
Avatar of ST3VO

ASKER

There's no actual error....it's just that I get double quotes twice

""."" instead of "." ...do you know why?

thx for your reply :o)

may be something with the code .... may i have a look on the complete code ... or may from the csv file itself
Avatar of ST3VO

ASKER

Sure here is the complete code attached below:

thanks a lot!!!
<?php
  	
 
//ini_set('short_open_tag', TRUE); //ENABLE SHORT TAGS
 
header("Content-Transfer-Encoding: binary");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"file.xml\";" );
        $file = file("data.csv");
        $fieldsep = ",";
echo"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<gallery xmlns:media="http://search.yahoo.com/mrss/">
 
        <settings>
                <mediaFolder type="large" media="video">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="video">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="swf">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="swf">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="image">images/</mediaFolder>
                <mediaFolder type="thumbnail" media="image">images/thumbs/</mediaFolder>
        </settings>
 
 
<?php
        for ($i=1;$i< count($file);$i++) {
                $line = explode($fieldsep, $file[$i]);
                $line[6] = str_replace("\n"," ",$line[30]);
?>
 
<item FeedId="<?php echo $line[0]?>"
     Vehicle_ID="<?php echo $line[1]?>"
    FullRegistration="<?php echo $line[2]?>"
    Colour="<?php echo $line[3]?>"
    FuelType="<?php echo $line[4]?>"
    Year="<?php echo $line[5]?>"
    Mileage="<?php echo $line[6]?>"
    Bodytype="<?php echo $line[7]?>"
    Doors="<?php echo $line[8]?>"
    Make="<?php echo $line[9]?>"
    Model="<?php echo $line[10]?>"
    Variant="<?php echo $line[11]?>"
    EngineSize="<?php echo $line[12]?>"
    Price="<?php echo $line[13]?>"
    Transmission="<?php echo $line[14]?>"
    PictureRef1="<?php echo $line[15]?>"
    PictureRef2="<?php echo $line[16]?>"
    PictureRef3="<?php echo $line[17]?>"
    PictureRef4="<?php echo $line[18]?>"
    PictureRef5="<?php echo $line[19]?>"
    PictureRef6="<?php echo $line[20]?>"
    PictureRef7="<?php echo $line[21]?>"
    PictureRef8="<?php echo $line[22]?>"
    PictureRef9="<?php echo $line[23]?>"
    PictureRef10="<?php echo $line[24]?>"
    ServiceHistory="<?php echo $line[25]?>"
    PreviousOwners="<?php echo $line[26]?>"
    Description="<?php echo $line[27]?>"
    FourWheelDrive="<?php echo $line[28]?>"
    Options="<?php echo $line[29]?>"
    Comments="<?php echo $line[30]?>"
    New="<?php echo $line[31]?>"
    Used="<?php echo $line[32]?>"
    Site="<?php echo $line[33]?>"
    Origin="<?php echo $line[34]?>"
    V5="<?php echo $line[35]?>"
    Condition="<?php echo $line[36]?>"
    ExDemo="<?php echo $line[37]?>"
    FranchiseApproved="<?php echo $line[38]?>"
    TradePrice="<?php echo $line[39]?>"
    TradePriceExtra="<?php echo $line[40]?>"
    ServiceHistoryText="<?php echo $line[41]?>"
    
 
        <media:text><?php echo $line[4]?></media:text>
        <media:content Comments="<?php echo $line[30]?>" type="image/jpeg" width="600" height="450" />
</item>
<?php
        }
?>
 
</gallery>
 

Open in new window

Avatar of ST3VO

ASKER

Updated code with some fixes:

attached below:
<?php
  	
 
//ini_set('short_open_tag', TRUE); //ENABLE SHORT TAGS
 
header("Content-Transfer-Encoding: binary");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"file.xml\";" );
        $file = file("data.csv");
        $fieldsep = ",";
echo"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<gallery xmlns:media="http://search.yahoo.com/mrss/">
 
        <settings>
                <mediaFolder type="large" media="video">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="video">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="swf">video/</mediaFolder>
                <mediaFolder type="thumbnail" media="swf">video/thumbs/</mediaFolder>
                <mediaFolder type="large" media="image">images/</mediaFolder>
                <mediaFolder type="thumbnail" media="image">images/thumbs/</mediaFolder>
        </settings>
 
<?php
echo '<item url="http://127.0.0.1/3dwall/pages/1.html" windowType="_blank" popWidth="800" popHeight="600" imgSet1="1a.jpg" imgSet2="1b.jpg" imgSet3="1c.jpg" imgSet4="1d.jpg" imgSet5="1e.jpg" indexValue1="0" indexValue2="1" indexValue3="2" indexValue4="3" indexValue5="4"';
 
?>
<?php
        for ($i=1;$i< count($file);$i++) {
                $line = explode($fieldsep, $file[$i]);
                $line[6] = str_replace("\n"," ",$line[30]);
?>
 
    FeedId="<?php echo $line[0]?>"
    Vehicle_ID="<?php echo $line[1]?>"
    FullRegistration="<?php echo $line[2]?>"
    Colour="<?php echo $line[3]?>"
    FuelType="<?php echo $line[4]?>"
    Year="<?php echo $line[5]?>"
    Mileage="<?php echo $line[6]?>"
    Bodytype="<?php echo $line[7]?>"
    Doors="<?php echo $line[8]?>"
    Make="<?php echo $line[9]?>"
    Model="<?php echo $line[10]?>"
    Variant="<?php echo $line[11]?>"
    EngineSize="<?php echo $line[12]?>"
    Price="<?php echo $line[13]?>"
    Transmission="<?php echo $line[14]?>"
    PictureRef1="<?php echo $line[15]?>"
    PictureRef2="<?php echo $line[16]?>"
    PictureRef3="<?php echo $line[17]?>"
    PictureRef4="<?php echo $line[18]?>"
    PictureRef5="<?php echo $line[19]?>"
    PictureRef6="<?php echo $line[20]?>"
    PictureRef7="<?php echo $line[21]?>"
    PictureRef8="<?php echo $line[22]?>"
    PictureRef9="<?php echo $line[23]?>"
    PictureRef10="<?php echo $line[24]?>"
    ServiceHistory="<?php echo $line[25]?>"
    PreviousOwners="<?php echo $line[26]?>"
    Description="<?php echo $line[27]?>"
    FourWheelDrive="<?php echo $line[28]?>"
    Options="<?php echo $line[29]?>"
    Comments="<?php echo $line[30]?>"
    New="<?php echo $line[31]?>"
    Used="<?php echo $line[32]?>"
    Site="<?php echo $line[33]?>"
    Origin="<?php echo $line[34]?>"
    V5="<?php echo $line[35]?>"
    Condition="<?php echo $line[36]?>"
    ExDemo="<?php echo $line[37]?>"
    FranchiseApproved="<?php echo $line[38]?>"
    TradePrice="<?php echo $line[39]?>"
    TradePriceExtra="<?php echo $line[40]?>"
    ServiceHistoryText="<?php echo $line[41]?>"
    
 
        <media:text><?php echo $line[4]?></media:text>
        <media:content Comments="<?php echo $line[30]?>" type="image/jpeg" width="600" height="450" />
</item>
<?php
        }
?>
 
</gallery>
 

Open in new window