Files
cdnPRO/infomech-pl/vidis.php
2024-10-25 16:01:25 +02:00

321 lines
11 KiB
PHP

<?php
class SimpleXMLElementExtended extends SimpleXMLElement
{
private function addCDataToNode(SimpleXMLElement $node, $value = '')
{
if ($domElement = dom_import_simplexml($node))
{
$domOwner = $domElement->ownerDocument;
$domElement->appendChild($domOwner->createCDATASection("{$value}"));
}
}
public function addChildWithCData($name = '', $value = '')
{
$newChild = parent::addChild($name);
if ($value) $this->addCDataToNode($newChild, "{$value}");
return $newChild;
}
public function addCData($value = '')
{
$this->addCDataToNode($this, "{$value}");
}
}
// $dom = new DOMDocument;
// libxml_use_internal_errors(true);
// // Załaduj HTML
// $html = file_get_contents('https://www.vidis.pl/'); // Zastąp ścieżką do pliku HTML
// $dom->loadHTML($html);
// $categories = [];
// // Znajdź element <ul> o ID 'dropdown-categories'
// $dropdownCategories = $dom->getElementById('dropdown-categories');
// $y = 0;
// $x = 0;
// if ($dropdownCategories) {
// foreach ($dropdownCategories->childNodes as $child) {
// if ($child->nodeType == XML_ELEMENT_NODE && $child->nodeName == 'li') {
// // Sprawdź, czy element <li> zawiera kategorię
// $a = $child->getElementsByTagName('a');
// if ($a->length > 0) {
// $categoryName = trim($a->item(0)->nodeValue);
// $categoryUrl = 'https://www.vidis.pl' . $a->item(0)->getAttribute('href');
// $globalUrls[$y]['name'] = $categoryName;
// $globalUrls[$y]['url'] = $categoryUrl;
// // Znajdź podkategorie
// $subcategories = [];
// $z = 0;
// $y++;
// foreach ($child->getElementsByTagName('ul') as $subUl) {
// foreach ($subUl->getElementsByTagName('li') as $subLi) {
// $subA = $subLi->getElementsByTagName('a');
// if ($subA->length > 0) {
// $subCatName = trim($subA->item(0)->nodeValue);
// $subCatUrl = 'https://www.vidis.pl' . $subA->item(0)->getAttribute('href');
// $subcategories[$z]['name'] = $subCatName;
// $subcategories[$z]['url'] = $subCatUrl;
// $globalUrls[$y]['url'] = $subCatUrl;
// $globalUrls[$y]['name'] = $categoryName . '|' . $subCatName;
// $z++;
// $y++;
// }
// }
// }
// $categories[$x]['name'] = $categoryName;
// $categories[$x]['url'] = $categoryUrl;
// $categories[$x]['subcategories'] = $subcategories;
// $x++;
// }
// }
// }
// }
// foreach ($globalUrls as $key => $val) {
// // Pobieranie zawartości strony
// $curl = curl_init();
// curl_setopt($curl, CURLOPT_URL, $val['url']);
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// $html = curl_exec($curl);
// curl_close($curl);
// if ($html) {
// // Ładowanie HTML do DOMDocument
// $dom->loadHTML($html);
// $globalUrls[$key]['pages'] = 1;
// // Szukanie paginacji
// $pagination = $dom->getElementsByTagName('ul');
// foreach ($pagination as $ul) {
// if ( strpos( $ul->getAttribute('class'), 'pagination' ) !== false ) {
// $pages = $ul->getElementsByTagName('a');
// $lastPage = trim($pages->item($pages->length - 2)->nodeValue);
// $globalUrls[$key]['pages'] = $lastPage;
// break;
// }
// }
// }
// }
// // zapisz jako json do pliku categories.json
// file_put_contents('categories.json', json_encode($globalUrls, JSON_PRETTY_PRINT));
// // Pobierz dane z pliku categories.json i zamień na tablicę
// $jsonData = file_get_contents('categories.json');
// $categories = json_decode($jsonData, true);
// // Weź pierwszy element tablicy
// $firstCategory = array_shift($categories);
// // Tablica ma zmienne: name, url, pages
// $name = $firstCategory['name'];
// $url = $firstCategory['url'];
// $pages = $firstCategory['pages'];
// // Pętla po podstronach, dopisując do URL ?p=$i, aż do wartości równiej 'pages', i pobranie danych z każdej podstrony
// for ($i = 1; $i <= $pages; $i++) {
// $pageUrl = $url . '?p=' . $i;
// $ch = curl_init();
// curl_setopt($ch, CURLOPT_URL, $pageUrl);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_AUTOREFERER, false);
// curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com");
// curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
// curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// curl_setopt($ch, CURLOPT_HEADER, 0);
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
// curl_setopt($ch, CURLOPT_TIMEOUT, 60);
// $html = curl_exec($ch);
// curl_close($ch);
// $doc = new \DOMDocument();
// libxml_use_internal_errors(true);
// $doc->loadHTML($html);
// $xpath = new DOMXpath($doc);
// $urls_tmp = $xpath->query("//*[@id=\"ajax_products_list\"]/li");
// for ($z = 1; $z <= count($urls_tmp); $z++)
// {
// $link = $xpath->query("//*[@id=\"ajax_products_list\"]/li[" . $z . "]/article[@class='product']/div[@class='row']/a[starts-with(@class,'btn')]/@href")->item(0);
// $urls[] = trim(strip_tags($link->textContent)) . '||' . $name;
// }
// // pobierz zawartośc pliku urls.txt
// $file = file_get_contents('urls.txt');
// // dodaj nowe adresy url
// $file .= implode("\n", $urls) . "\n";
// // zapisz do pliku urls.txt
// file_put_contents('urls.txt', $file);
// }
// // Usuń pierwszy element tablicy $categories
// // Pozostałe elementy zapisz znowu do pliku categories.json
// file_put_contents('categories.json', json_encode($categories));
// // Wyświetl komunikat o ilości pozostałych kategorii
// echo "Pozostało " . count($categories) . " kategorii w pliku categories.json.";
// // jeżeli zostało więcej niż 1 strona odśwież stronę
// if (count($categories) > 0) {
// echo '<script>setTimeout(function(){location.reload();}, 1000);</script>';
// }
/*
// Ścieżka do pliku źródłowego
$inputFile = 'urls.txt';
// Ścieżka do pliku wynikowego
$outputFile = 'vidis-urls-unique.txt';
// Przechowuje unikalne adresy URL
$uniqueUrls = [];
// Przechowuje linie do zapisania
$linesToWrite = [];
// Otwórz plik źródłowy do odczytu
$fileHandle = fopen($inputFile, "r");
if ($fileHandle) {
while (($line = fgets($fileHandle)) !== false) {
// Rozdziel linię na URL i resztę tekstu
$parts = explode('||', $line);
$url = $parts[0];
// Sprawdź, czy adres URL jest już w tablicy
if (!in_array($url, $uniqueUrls)) {
$uniqueUrls[] = $url; // Dodaj adres URL do tablicy unikalnych adresów URL
$linesToWrite[] = $line; // Dodaj linię do zapisania
}
}
fclose($fileHandle);
} else {
echo "Nie można otworzyć pliku: $inputFile";
}
// Zapisz unikalne linie do nowego pliku
if (file_put_contents($outputFile, $linesToWrite) === false) {
echo "Błąd podczas zapisywania do pliku: $outputFile";
} else {
echo "Plik został zapisany: $outputFile";
}*/
// Pobierz dane z pliku urls.txt i zamień na tablicę, rozdzielając każdą linię na 2 elementy: url i category po ||
$urlsData = file_get_contents('vidis-urls-unique.txt');
$lines = explode("\n", $urlsData);
$urls = [];
foreach ($lines as $line) {
if (!empty($line)) {
list($url, $category) = explode('||', $line);
$urls[] = ['url' => $url, 'category' => $category];
}
}
// Pobierz pierwszy element
$firstElement = array_shift($urls);
echo '<pre>';
print_r($firstElement);
echo '</pre>';
// Pobierz stronę przez URL
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $firstElement['url']);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );
$html = curl_exec( $ch );
curl_close( $ch );
if ( $html === false )
{
echo "Błąd cURL: " . curl_error( $ch ) . " (kod błędu: " . curl_errno( $ch ) . ")";
}
else
{
$doc = new \DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
}
unset($product);
// Tutaj mój kod
$product['url'] = $url;
$product['category'] = $firstElement['category'];
$reference = $xpath->query("//*[@id=\"product\"]/div[@class='row']/div[starts-with(@class,'col-xs-12')]/header/h2/span")->item(0);
$product['reference'] = $reference->textContent;
$name = $xpath->query("//*[@id=\"product\"]/div[@class='row']/div[starts-with(@class,'col-xs-12')]/header/h1")->item(0);
$product['name'] = $name->textContent;
$price = $xpath->query("//*[@id=\"product\"]/div[@class='row']/div[starts-with(@class,'col-xs-12')]/section[starts-with(@class,'product-prices')]/div[@class='wrapper-prices']/span[@class='price']")->item(0);
$product['price'] = str_replace( ' zł netto', '', trim( $price->textContent ) );
$xml_file = 'vidis-products.xml';
if ( file_exists( $xml_file ) )
{
$xml_content = file_get_contents($xml_file);
$xml = new SimpleXMLElementExtended($xml_content);
}
else
{
$xml = new SimpleXMLElementExtended('<?xml version="1.0"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0"/>');
$xml -> addChild('title', 'vidis');
$xml -> addChild('updated', date('Y-m-d'));
}
$productXml = $xml->addChild('item');
$productXml->addChild('reference', $product['reference']);
$productXml->addChild('title', $product['name']);
if ($product['price'])
$productXml->addChild('price', $product['price']);
$productXml->addChildWithCData('category', $product['category']);
$xml -> asXML( $xml_file );
// Pozostałe dane z pliku urls (bez pierwszego) znowu zapisz do pliku urls.txt
$remainingUrls = array_map(function($urlData) {
return $urlData['url'] . '||' . $urlData['category'];
}, $urls);
file_put_contents('vidis-urls-unique.txt', implode("\n", $remainingUrls));
// Wyświetl komunikat ile URL zostało do pobrania
echo "Pozostało " . count($remainingUrls) . " URLi do pobrania.";
// jeżeli zostało więcej niż 1 strona odśwież stronę
if (count($remainingUrls) > 0) {
echo '<script>setTimeout(function(){location.reload();}, 1);</script>';
}
// Ścieżka do pliku XML
// $xmlFile = 'vidis-products.xml';
// // Wczytaj plik XML
// $xml = simplexml_load_file($xmlFile);
// // Tablica do śledzenia unikalnych referencji
// $uniqueReferences = [];
// // Nowy obiekt SimpleXML do przechowywania wyników
// $newXml = new SimpleXMLElement('<feed xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0"/>');
// // Kopiuj tytuł i datę aktualizacji
// $newXml->addChild('title', (string)$xml->title);
// $newXml->addChild('updated', (string)$xml->updated);
// // Przechodzenie przez każdy element i usuwanie duplikatów
// foreach ($xml->item as $item) {
// $reference = (string)$item->reference;
// // Sprawdź, czy referencja jest już w tablicy
// if (!in_array($reference, $uniqueReferences)) {
// // Dodaj referencję do tablicy
// $uniqueReferences[] = $reference;
// // Dodaj element do nowego XML
// $newItem = $newXml->addChild('item');
// foreach ($item as $key => $value) {
// $newItem->addChild($key, (string)$value);
// }
// }
// }
// // Zapisz nowy plik XML
// $newXml->asXML('vidis-unique.xml');
?>