@@ -100,6 +100,8 @@ class Parser
100
100
*/
101
101
private $ messageNumber ;
102
102
103
+ private ?string $ sourceEncoding = null ;
104
+
103
105
/**
104
106
* @var array<string,string>
105
107
*/
@@ -141,8 +143,13 @@ class Parser
141
143
*/
142
144
public function parse (): self
143
145
{
146
+ $ rawSegments = $ this ->getRawSegments ();
147
+ if ($ this ->sourceEncoding && isset (self ::$ charsets [$ this ->syntaxID ]) && self ::$ charsets [$ this ->syntaxID ] !== $ this ->sourceEncoding ) {
148
+ $ rawSegments = $ this ->convertEncoding ($ this ->rawSegments , $ this ->sourceEncoding , self ::$ charsets [$ this ->syntaxID ]);
149
+ }
150
+
144
151
$ i = 0 ;
145
- foreach ($ this -> getRawSegments () as $ line ) {
152
+ foreach ($ rawSegments as $ line ) {
146
153
$ i ++;
147
154
148
155
// Null byte and carriage return removal. (CR+LF)
@@ -310,16 +317,38 @@ public function setStrict(bool $strict):void
310
317
$ this ->strict = $ strict ;
311
318
}
312
319
320
+ public function setSourceEncoding (string $ sourceEncoding ): void
321
+ {
322
+ $ this ->sourceEncoding = $ sourceEncoding ;
323
+ }
324
+
313
325
/**
314
326
* Get parsed lines/segments.
315
327
*/
316
- public function get (): array
328
+ public function get (? string $ encoding = null ): array
317
329
{
318
330
if (empty ($ this ->parsedfile )) {
319
331
$ this ->parse ();
320
332
}
321
-
322
- return $ this ->parsedfile ;
333
+
334
+ if (null === $ encoding ) {
335
+ return $ this ->parsedfile ;
336
+ }
337
+
338
+ return $ this ->convertEncoding ($ this ->parsedfile , self ::$ charsets [$ this ->syntaxID ], $ encoding );
339
+ }
340
+
341
+ private function convertEncoding ($ data , string $ from , string $ to )
342
+ {
343
+ if (is_array ($ data )) {
344
+ foreach ($ data as $ k => $ v ) {
345
+ $ data [$ k ] = $ this ->convertEncoding ($ v , $ from , $ to );
346
+ }
347
+ } elseif (is_string ($ data )) {
348
+ $ data = function_exists ('iconv ' ) ? iconv ($ from , $ to . '//TRANSLIT ' , $ data ) : mb_convert_encoding ($ data , $ to , $ from );
349
+ }
350
+
351
+ return $ data ;
323
352
}
324
353
325
354
/**
0 commit comments