1

This is may xml file

<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<title>werwer</title>
<link>werwerwe</link>

<item>
<g:id>704667</g:id>
<title>Nike</title>
<description>erterterter</description>
</item>

<item>
<g:id>4456456</g:id>
<title>Nike</title>
<description>erterterter</description>
</item>

</channel></rss>

how to parse that xml file, I have script but it doesnt work

if (file_exists('products.xml')) {
    $xml = simplexml_load_file('products.xml');

    print_r($xml);
} else {
    exit('Failed to open products.xml.');
}

any idea how to get information between g:id?

adrian
  • 23
  • 2

1 Answers1

1

You need to get an apply the namespace to the children. http://php.net/manual/en/simplexmlelement.getnamespaces.php

<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
    <channel>
        <title>werwer</title>
        <link>werwerwe</link>

        <item>
            <g:id>704667</g:id>
            <title>Nike</title>
            <description>erterterter</description>
        </item>

        <item>
            <g:id>4456456</g:id>
            <title>Nike</title>
            <description>erterterter</description>
        </item>

    </channel>
</rss>';

$xml = simplexml_load_string($xml);
$ns = $xml->getNamespaces(true);

foreach ($xml->channel->item as $item) {
    echo $item->children($ns['g'])->id.PHP_EOL;
}
/*
704667
4456456
*/

https://3v4l.org/t2D84

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106