Thomas
Thomas

Reputation: 1706

convert text file to xml in php

I have a file.txt which contains the following:

[General]
FileVersion=3
NumberOfWaypoints=12
[Point1]
Latitude=50.8799722
Longitude=4.7008664
Radius=10
Altitude=25
ClimbRate=30
DelayTime=2
WP_Event_Channel_Value=100
Heading=0
Speed=30
CAM-Nick=0
Type=1
Prefix=P
[Point2]
...

I would like to extract the data from it to parse it to an xml file or database later.

I've tried using php functions like substr and strrpos but I always run into trouble because the lenght of the values like altitude and climbrate could be "20" or "2" or "200". Also when using strrpos and the value of the "needle" occurs multiple times; i don't get the right value.

Anybody came across this type of problem before?

(edit: I loaded the file into a php string)

Upvotes: 0

Views: 3115

Answers (2)

narruc
narruc

Reputation: 350

You could try this:

<?php
$array = parse_ini_string($string);

$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($array, array ($xml, 'addChild'));
echo $xml->asXML();
?>

Upvotes: 2

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

Or you could try this:

<?php
//or create $file from file_get_contents('file.txt');
$file = "[General]
FileVersion=3
NumberOfWaypoints=12
[Point1]
Latitude=50.8799722
Longitude=4.7008664
Radius=10
Altitude=25
ClimbRate=30
DelayTime=2
WP_Event_Channel_Value=100
Heading=0
Speed=30
CAM-Nick=0
Type=1
Prefix=P
[Point2]";

//or create $array with file('file.txt');
$array = explode("\n",$file);

//Create and output xml from the given array
header('Content-Type: text/xml');
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><points/>');

foreach($array as $k=>$v){
    if(substr($v,0,1)=='['){
        $node = $xml->addChild(str_replace(array('[',']'),'',$v));
    }else{
        list($key,$value) = explode('=',$v,2);
        $node->addChild($key, trim($value));
    }
}

//DOMDocument to format code output
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());

echo $dom->saveXML();

/*Result:
<?xml version="1.0" encoding="UTF-8"?>
<points>
  <General>
    <FileVersion>3</FileVersion>
    <NumberOfWaypoints>12</NumberOfWaypoints>
  </General>
  <Point1>
    <Latitude>50.8799722</Latitude>
    <Longitude>4.7008664</Longitude>
    <Radius>10</Radius>
    <Altitude>25</Altitude>
    <ClimbRate>30</ClimbRate>
    <DelayTime>2</DelayTime>
    <WP_Event_Channel_Value>100</WP_Event_Channel_Value>
    <Heading>0</Heading>
    <Speed>30</Speed>
    <CAM-Nick>0</CAM-Nick>
    <Type>1</Type>
    <Prefix>P</Prefix>
  </Point1>
  <Point2/>
</points>
*/

Upvotes: 1

Related Questions