I want to create a php array with all xml tags in a remote XML file. The depth and structure of the XML file will be unknown, so that’s why maybe recursive function will be the best solution. Anyway, I will add a sample just for the case of study. Here is my code so far:
$xml = file_get_contents('https://sxy.bg/test.xml');
$xml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
the xml in the file is:
$xml = '<rss version="2.0">
<channel>
<title>Test Store</title>
<link>https://www.sxy.bg/</link>
<description>SXY</description>
<item>
<g:id>8797</g:id>
<g:title>Product Title 8797</g:title>
<g:description>Product description 8797</g:description>
<g:link>https://www.sxy.bg/store/8797</g:link>
<g:image_link>https://www.sxy.bg/images/store/8797.jpg</g:image_link>
<g:brand>Olight</g:brand>
<g:condition>new</g:condition>
<g:availability>in stock</g:availability>
<g:price>99.00 EUR</g:price>
<g:shipping>
<g:country>BG</g:country>
<g:service>Standard</g:service>
<g:price>4.95 EUR</g:price>
</g:shipping>
<g:google_product_category>Auto</g:google_product_category>
<g:custom_label_0>Hot Offers</g:custom_label_0>
</item>
<item>
<g:id>8813</g:id>
<g:title>Product Title 8813</g:title>
<g:description>Product description 8813</g:description>
<g:link>https://www.sxy.bg/store/8813</g:link>
<g:image_link>https://www.sxy.bg/images/store/8813.jpg</g:image_link>
<g:brand>Olight</g:brand>
<g:condition>new</g:condition>
<g:availability>in stock</g:availability>
<g:price>305.00 EUR</g:price>
<g:shipping>
<g:country>BG</g:country>
<g:service>Standard</g:service>
<g:price>4.95 EUR</g:price>
</g:shipping>
<g:google_product_category>Auto</g:google_product_category>
<g:custom_label_0>Hot Offers</g:custom_label_0>
</item>
<item>
<g:id>8809</g:id>
<g:title>Product Title 8809</g:title>
<g:description>Product description 8809</g:description>
<g:link>https://www.sxy.bg/store/8809</g:link>
<g:image_link>https://www.sxy.bg/images/store/8809.jpg</g:image_link>
<g:brand>Olight</g:brand>
<g:condition>new</g:condition>
<g:availability>in stock</g:availability>
<g:price>375.00 EUR</g:price>
<g:shipping>
<g:country>BG</g:country>
<g:service>Standard</g:service>
<g:price>4.95 EUR</g:price>
</g:shipping>
<g:google_product_category>Auto</g:google_product_category>
<g:custom_label_0>Hot Offers</g:custom_label_0>
</item>
</channel>
</rss>';
The desired array format is:
array("channel", "title", "Link","description", "item", "g:id","g:title", "g:description","g:link","g:image_link","g:brand","g:condition", "g:availability","g:price","g:shipping","g:country","g:service","g:google_product_category","g:custom_label_0");
The array should consist only unique tags.. What would be the best approach for the task?
Thanks for your time
>Solution :
If you simply want all the unique tag names, you could just use a simple regex
$numTags = preg_match_all('|<([^/> ]+)|', $xml, $matches);
$tagNames = array_unique($matches[1]);