|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Xparse\Parser\Helper; |
|
4
|
|
|
|
|
5
|
|
|
use GuzzleHttp\Psr7\Response; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class EncodingConverter |
|
9
|
|
|
* @package Xparse\Parser\Helper |
|
10
|
|
|
*/ |
|
11
|
|
|
class EncodingConverter |
|
12
|
|
|
{ |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @var array|null |
|
16
|
|
|
*/ |
|
17
|
|
|
private static $supportedEncodings = null; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @param Response $response |
|
21
|
|
|
* @param $html |
|
22
|
|
|
* @param $convertToEncoding |
|
23
|
|
|
* @return mixed |
|
24
|
|
|
*/ |
|
25
|
3 |
|
public static function convertTo(Response $response, $html, $convertToEncoding) { |
|
26
|
3 |
|
$contentType = $response->getHeaderLine('content-type'); |
|
27
|
|
|
|
|
28
|
3 |
|
if (!empty($contentType)) { |
|
29
|
|
|
preg_match("!^.*charset=([A-Za-z0-9-]{4,})$!", $contentType, $contentTypeData); |
|
30
|
|
|
$encoding = !empty($contentTypeData[1]) ? strtoupper(trim($contentTypeData[1])) : ''; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
3 |
|
if (empty($encoding)){ |
|
34
|
3 |
|
preg_match("!.*<meta.*charset=[\"']?[ \t]*([A-Za-z0-9-]{4,})[ \t]*[\"']!mi", $html, $metaContentType); |
|
35
|
3 |
|
$encoding = !empty($metaContentType[1]) ? strtoupper(trim($metaContentType[1])) : ''; |
|
36
|
3 |
|
} |
|
37
|
|
|
|
|
38
|
3 |
|
$supportedEncodings = self::getSupportedEncodings(); |
|
39
|
3 |
|
if (in_array($encoding, $supportedEncodings)) { |
|
40
|
|
|
$html = mb_convert_encoding($html, $convertToEncoding, $encoding); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
3 |
|
return $html; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* @return array |
|
49
|
|
|
*/ |
|
50
|
3 |
|
private static function getSupportedEncodings() { |
|
51
|
3 |
|
if (self::$supportedEncodings !== null) { |
|
52
|
2 |
|
return self::$supportedEncodings; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
1 |
|
self::$supportedEncodings = []; |
|
56
|
1 |
|
foreach (mb_list_encodings() as $encoding) { |
|
57
|
1 |
|
if ($encoding == 'UTF-8' or $encoding == 'UTF8') { |
|
58
|
1 |
|
continue; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
1 |
|
self::$supportedEncodings[] = $encoding; |
|
62
|
1 |
|
self::$supportedEncodings = array_merge(self::$supportedEncodings, mb_encoding_aliases($encoding)); |
|
63
|
1 |
|
} |
|
64
|
|
|
|
|
65
|
1 |
|
return self::$supportedEncodings; |
|
66
|
|
|
} |
|
67
|
|
|
} |