Dennis G
Dennis G

Reputation: 21788

Translate PHP array to C# array/DataSet

I'm trying to write a simple Windows Forms application to make translation of PHP based language files easier.

The forms application is pretty simple:

  1. Load PHP file
  2. Create C# array from php array (see below for PHP details)
  3. For each item in array display two boxes: Original + Translation
  4. User enters his translations in Box 2
  5. User clicks Next, Repeat Step 3+4
  6. User clicks Save, the translated array is saved to a new file.

The PHP file (language.php) is of the simplest nature:

<?php
$language['errormsg'] = 'This is my error message';
$language['forward'] = 'Forward';
$language['testing'] = 'Beta';
?>

How do I "convert" (parse) this simple PHP file into a C# array, DataSet or anything I can loop on? Loading the file as a string via System.IO.File.ReadAllText is easy, I just don't know how to parse it in a smart way

Upvotes: 0

Views: 1675

Answers (4)

Paolo Falabella
Paolo Falabella

Reputation: 25844

Here's a regex to pick the values enclosed in single quotes, which are all you actually need.

'[^'\r\n]*'

for instance:

  string text = @"$language['errormsg'] = 'This is my error message';";
  string pat = @"'[^'\r\n]*'";

  Regex r = new Regex(pat, RegexOptions.IgnoreCase);
  Match m = r.Match(text);
  while (m.Success) 
  {
     Console.WriteLine(m.Value);
     m = m.NextMatch();
  }

output:

'errormsg'
'This is my error message'

Also note that you can read the original file line by line with

foreach (string line in File.ReadLines(@"[your php file path]"))
{
   // process line
}

Upvotes: 1

Jean Louis
Jean Louis

Reputation: 1555

If you want to get data from php file you may use the Regex class. These are regular expressions.

Upvotes: 0

Edgar
Edgar

Reputation: 4488

I'd suggest using Regular Expressions. Once you've loaded the file, run a regex that searches for array syntax and picks up the necessary bits, then put those bits into a Dictionary<string, string>.

To loop through the dictionary, do

foreach (var message in myDictionary)
{
    // message.Key or message.Value to access the bits
}

Upvotes: 1

Greg
Greg

Reputation: 21909

Rather than writing your own PHP parser, I'd recommend using an inbuilt PHP function to output the data into a format readable by C#, such as XML or JSON.

Then your simple Windows Forms application can read the data natively.

Upvotes: 0

Related Questions