Files
cdnPRO/naturalbabycare.eu/xml-convert.php

48 lines
1.6 KiB
PHP

<?php
$file = file_get_contents('https://feed.syntogether.com/skroutz/xml?shop=5f4930.myshopify.com');
if ($file === false) {
die('Błąd: Nie udało się pobrać pliku XML.');
}
// Definiujemy przestrzeń nazw Google Merchant
$gNamespace = 'http://base.google.com/ns/1.0';
// Tworzymy obiekt XML na podstawie pobranych danych
$xml = new SimpleXMLElement($file, LIBXML_NOERROR | LIBXML_NOCDATA);
// Sprawdzamy, czy XML jest poprawny i czy zawiera produkty
if (!$xml || !isset($xml->products) || !isset($xml->products->product)) {
die('Błąd: Nieprawidłowa struktura XML.');
}
// **Tworzymy NOWY obiekt SimpleXMLElement, aby od początku ustawić przestrzeń nazw**
$xmlString = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xmlString .= '<products xmlns:g="' . $gNamespace . '">' . "\n";
// Iterujemy przez produkty i dodajemy poprawnie element <g:gtin>
foreach ($xml->products->product as $product) {
$ean = (string) $product->ean;
// Usuwamy potencjalne znaczniki HTML i białe znaki
$ean = strip_tags(trim($ean));
$xmlString .= " <product>\n";
foreach ($product->children() as $child) {
$childValue = strip_tags(trim((string) $child)); // Usuwamy HTML
$xmlString .= " <{$child->getName()}>{$childValue}</{$child->getName()}>\n";
}
if (!empty($ean)) {
$xmlString .= " <g:gtin>{$ean}</g:gtin>\n";
}
$xmlString .= " </product>\n";
}
$xmlString .= "</products>\n";
// **Zapisujemy poprawny XML do pliku**
file_put_contents('feed-xml.xml', $xmlString);
echo '<p>wygenerowano <a href="https://cdn.projectpro.pl/naturalbabycare.eu/feed-xml.xml" target="_blank">feed-xml.xml</a></p>';
?>