sveden-parser/app/library/ContingentParser.php

93 lines
2.8 KiB
PHP
Raw Normal View History

2024-08-08 12:32:27 +02:00
<?php
namespace App\Library;
use App\Library\ContingentRow;
2024-08-08 12:32:27 +02:00
class ContingentParser
2024-08-08 12:32:27 +02:00
{
private \DOMXPath $xpath;
private string $template;
private const FIELDS = [
"eduCode" => "td",
"eduName" => "td",
"eduLevel" => "td",
"eduForm" => "td",
// "numberBF" => "th",
// "numberBFF" => "th",
// "numberBR" => "th",
// "numberBRF" => "th",
// "numberBM" => "th",
// "numberBMF" => "th",
// "numberP" => "th",
// "numberPF" => "th",
"numberAll" => ["th", "td"]
2024-08-08 12:32:27 +02:00
];
public function __construct(string $html, string $template)
{
libxml_use_internal_errors(true);
$dom = new \DOMDocument(
// encoding: "UTF-8"
);
$encoding = mb_detect_encoding($html, 'UTF-8, windows-1251');
if ($encoding != "UTF-8") {
$html = mb_convert_encoding(
$html,
'UTF-8',
$encoding
);
$html = str_replace('windows-1251','utf-8', $html);
}
$dom->loadHTML(mb_convert_encoding($html,'HTML-ENTITIES','UTF-8'));
2024-08-08 12:32:27 +02:00
$this->xpath = new \DOMXPath($dom);
$this->template = $template;
}
private function parse(): array
{
$data = array();
foreach (self::FIELDS as $field => $tag) {
if (!is_array($tag)) {
$data[$field] = $this->xpath->query($this->template . $tag . "[@itemprop=\"$field\"]");
} else {
$th = $this->xpath->query($this->template . $tag[0] . "[@itemprop=\"$field\"]");
$td = $this->xpath->query($this->template . $tag[1] . "[@itemprop=\"$field\"]");
$data[$field] = $th->length > $td->length ? $th : $td;
}
2024-08-08 12:32:27 +02:00
}
return $data;
}
public function getDataTable() : array
{
$data = $this->parse();
$records = array();
// var_dump($data);
// exit(0);
if ($data == null) return [];
2024-08-08 12:32:27 +02:00
$equal = $data['eduName']->length;
foreach ($data as $field) {
if ($field->length == 0) {
return [];
}
if ($field->length != $equal) {
return [];
}
}
for ($i = 0; $i < $data['eduCode']->length; $i++) {
$contingentRow = new ContingentRow(
2024-08-08 12:32:27 +02:00
$data['eduCode']->item($i)->textContent,
$data['eduName']->item($i)->textContent,
$data['eduLevel']->item($i)->textContent,
$data['eduForm']->item($i)->textContent,
(int)$data['numberAll']->item($i)->textContent
);
$records[] = $contingentRow->getData();
2024-08-08 12:32:27 +02:00
}
return $records;
}
}