How to Properly Read Colon Tags (<p:id>) in google_merchant.xml in PHP

There is no easy way to read the <p:id> tag in xml. You should analyze the xml for a description of the xmlns:g="http://base.google.com/ns/1.0" space. If such a line is present, you can use xpath, and if not, there is an easier way to read such a tag.

Example xml:

<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">
  <channel>
    <title>Example of a store</title>
    <link>https://example.com</link>
    <description>Product feed</description>

    <item>
      <g:id>12345</g:id>
      <g:title>Product 1</g:title>
      <g:price>199.00 UAH</g:price>
    </item>

    <item>
      <g:id>12346</g:id>
      <g:title>Product 2</g:title>
      <g:price>299.00 UAH</g:price>
    </item>
  </channel>
</rss>

There is xmlns:g="http://base.google.com/ns/1.0", then we use xpath:

<?php
$xml = simplexml_load_string($xmlString);
// Register the namespace for working via xpath
$xml->registerXPathNamespace('g', 'http://base.google.com/ns/1.0');

// Move item to variable
$items = $xml->xpath('//item');
$result = [];

foreach ($items as $item) {
    $id    = (string) $item->xpath('g:id')[0];
    $title = (string) $item->xpath('g:title')[0];
    $price = (string) $item->xpath('g:price')[0];

    $result[] = [
        'id'    => $id,
        'title' => $title,
        'price' => $price,
    ];
}
var_dump($result);

The construction for accessing the required tag is defined as "$item->xpath('g:id')[0]".

When there is no xmlns:g="http://base.google.com/ns/1.0":

<?php
$xml = simplexml_load_string($xmlString);

$result = [];
foreach ($xml->channel->item as $item) {
    $result[] = [
        'id'    = (string) $item->{'g:id'};
        'title' = (string) $item->{'g:title'};
        'price' = (string) $item->{'g:price'};
    ];
    // OR
    // $result['id'] = (string)$item->children('g', true)->id;
}
var_dump($result);

You can use the $item->children('g', true)->id construction, or you can make it even shorter and more readable, for example, accessing the class via a property$item->{'g:id'}. This is the same as accessing a regular class.

<?php
$obj = new stdClass();
$obj->{'g:field'} = 'value';
var_dump($obj->{'g:field'});

461 0

Comments

Be the first to review this item. Share your rating and review so that other customers can decide if this is the right item for them.
You have to log in to leave a comment. Sign in

Similar articles

Create and download CSV in PHP

Consider the possibility of quickly creating a CSV file with automatic file download. Consider the formation, separators and header for the ability to download the file.

Long-term storage of the basket in the online store

Consider options for popular options for storing goods in a shopping cart in an online store. Let's outline the pros and cons of such storage. Consider options for long-term storage of the basket.