Giter Site home page Giter Site logo

php-google-merchant-feed's Introduction

Google Merchant feed generator for PHP

Build Status

Installation

Install the package through Composer.

Run the Composer require command from the Terminal:

composer require vitalybaev/google-merchant-feed

Example

use Vitalybaev\GoogleMerchant\Feed;
use Vitalybaev\GoogleMerchant\Product;
use Vitalybaev\GoogleMerchant\Product\Shipping;
use Vitalybaev\GoogleMerchant\Product\Availability\Availability;

// Create feed object
$feed = new Feed("My awesome store", "https://example.com", "My awesome description");

// Put products to the feed ($products - some data from database for example)
foreach ($products as $product) {
    $item = new Product();
    
    // Set common product properties
    $item->setId($product->id);
    $item->setTitle($product->title);
    $item->setDescription($product->description);
    $item->setLink($product->getUrl());
    $item->setImage($product->getImage());
    if ($product->isAvailable()) {
        $item->setAvailability(Availability::IN_STOCK);
    } else {
        $item->setAvailability(Availability::OUT_OF_STOCK);
    }
    $item->setPrice("{$product->price} USD");
    $item->setGoogleCategory($product->category_name);
    $item->setBrand($product->brand->name);
    $item->setGtin($product->barcode);
    $item->setCondition('new');
    
    // Some additional properties
    $item->setColor($product->color);
    $item->setSize($product->size);

    // Shipping info
    $shipping = new Shipping();
    $shipping->setCountry('US');
    $shipping->setRegion('CA, NSW, 03');
    $shipping->setPostalCode('94043');
    $shipping->setLocationId('21137');
    $shipping->setService('UPS Express');
    $shipping->setPrice('1300 USD');
    $item->setShipping($shipping);

    // Set a custom shipping label and weight (optional)
    $item->setShippingLabel('ups-ground');
    $item->setShippingWeight('2.14');

    // Set a custom label (optional)
    $item->setCustomLabel('Some Label 1', 0);
    $item->setCustomLabel('Some Label 2', 1);
    
    // Add this product to the feed
    $feed->addProduct($item);
}

// Here we get complete XML of the feed, that we could write to file or send directly
$feedXml = $feed->build();

Working with attributes

Product class provides several methods for managing various attributes. But it doesn't cover all Google Merchant attributes. In case of nonexistent methods you should use one of the following:

  1. $product->setAttribute($attributeName, $attributeValue, $isCData = false) - sets attribute. Replaces old attribute if it existed.
  2. $product->addAttribute($attributeName, $attributeValue, $isCData = false) - adds one more attribute's value. For example feed can have multiple additional_image_link attributes.

TO-DO

  • Cover all Google Merchant feed properties
  • More tests
  • Your feedback?

License

The MIT License

Copyright (c) 2016 Vitaly Baev. vitalybaev.ru

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

php-google-merchant-feed's People

Contributors

incredimike avatar jakeday avatar krylov123 avatar michelmelo avatar ololower avatar samuell1 avatar tegansnyder avatar toniop99 avatar vitalybaev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-google-merchant-feed's Issues

Shipping Costs

Hi Vitaly ,

thank you for this nice one. It is very usefull for me.
At the moment i try to put shipping costs into my feed.
As far as i know for Australia, Austria, Belgium, Canada, Czechia, France, Germany, Ireland Israel, Italy, the Netherlands, Poland, South Korea, Spain, Switzerland, the UK, and the US this is a mandatory field.

It consists of:

  • optional country as ISO-3166
  • optional region/postal_code/location_id/location_group
  • optional service
  • mandatory(!) price

(see: https://support.google.com/merchants/answer/6324484)

Do you have any solutions for that?

README information adjust

In the README page, use Vitalybaev\GoogleMerchant\Product\Availability\Availability; will cause exception, but it is working in this path use Vitalybaev\GoogleMerchant\Product\Availability\Availability;

also;

$feedProduct->setAvailability(Availability::IN_STOCK); should be $item->setAvailability(Availability::IN_STOCK);

Price format in readme's example is misleading

In README.md, shipping price example is misleading as it looks like an amount in cents:

$shipping->setPrice('1300 USD');

It expects price in ISO 4217 format + max value is 1000 as seen here https://support.google.com/merchants/answer/6324484 so example probably should be:

$shipping->setPrice('13.50 USD');

same with product price https://support.google.com/merchants/answer/6324371, it could include a comment to clarify:

$item->setPrice("{$product->price} USD"); //ex: "89.90 USD"

What do you think ?

Please insert parameters on products.php

/**
* Sets identifier_exists code of the product.(YES / NO)
*
* @param string $identifier_exists
*
* @return $this
*/
public function setIdentifierExists($identifier_exists)
{
$this->setAttribute('identifier_exists', $identifier_exists, false);
return $this;
}

Parse error: syntax error, unexpected 'NEW' (T_NEW) in vendor/vitalybaev/google-merchant-feed/src/Product.php on line 306

Hi,

I use PHP 5.5 And show error.

public function setCondition($condition)
    {
        if (!in_array($condition, [
            Condition::NEW, Condition::REFURBISHED, Condition::USED,
        ])) {
            throw new InvalidArgumentException("Invalid condition property");
        }
        $this->setAttribute('condition', $condition, false);
        return $this;
    }

i changed it to be:

public function setCondition($condition)
{

    $this->setAttribute('condition', $condition, false);
    return $this;
}

XML requires underscore

Situation:
The constants in php-google-merchant-feed/src/Product/Availability/Availability.php contain whitespaces.
Problem:
According to Google, "XML feeds or XML API: Underscores are required, and are converted into white space when received".
Solution suggestion:
Create separate XML constants or dynamically replace spaces with underscores in case of XML.

Fatal error: Declaration of Vitalybaev\GoogleMerchant\RssElement::xmlSerialize(Sabre\Xml\Writer $writer) must be compatible with Sabre\Xml\XmlSerializable::xmlSerialize(Sabre\Xml\Writer $writer): void

Hello !

I have this error when i try to launch the build of an XML feed, :
Fatal error: Declaration of Vitalybaev\GoogleMerchant\RssElement::xmlSerialize(Sabre\Xml\Writer $writer) must be compatible with Sabre\Xml\XmlSerializable::xmlSerialize(Sabre\Xml\Writer $writer): void

[app/src/Vitalybaev/GoogleMerchant/RssElement.php:28]

Is it a compatibilty problem with the last version of Sabre/Xml (4.0.2) ?

Thanks for your help.

Best.

Christophe

XML feed

Google Merchant Center (Shopping)

More than one Shipping?

Hi Vitaly,
seems like it is not possible to set up more than one shipping method right now? The Google Merchant docs state that you can enter up to 100 different shipping elements.

XML
To submit multiple delivery groups for an XML feed, include a separate attribute for each delivery group. You can submit up to 100 shipping attributes for each product.

<g:shipping>
   <g:country>US</g:country>
   <g:region>CA</g:region>
   <g:service>Express</g:service>
   <g:price>0 USD</g:price>
</g:shipping>
<g:shipping>
   <g:country>US</g:country>
   <g:region>OR</g:region>
   <g:service>Ground</g:service>
   <g:price>4.99 USD</g:price>
</g:shipping>
<g:shipping>
   <g:country>US</g:country>
   <g:region>WA</g:region>
   <g:service>Ground</g:service>
   <g:price>6.49 USD</g:price>
</g:shipping>

Any possibility of you adding an addShipping method?

Thanks!

Problem with class usage - help me please

Please, help me.
I have been collecting the realtime data in my cron file to generate the google merchant xml. After adjusting the variables, I try to use your class to generate the xml file, but the following error is occurring:

PHP Fatal error: Uncaught Vitalybaev\GoogleMerchant\Exception\InvalidArgumentException: Invalid availability property in /home/admin/web/mysite.com/public_html/cron/vendor/vitalybaev/google-merchant-feed/src/Product.php:130
Stack trace:
#0 /home/admin/web/mysite.com/public_html/cron/googleshopping.php(122): Vitalybaev\GoogleMerchant\Product->setAvailability('Dispon\xEDvel')
#1 {main}
thrown in /home/admin/web/mysite.com/public_html/cron/vendor/vitalybaev/google-merchant-feed/src/Product.php on line 130

This is my code:

<?php
$servername = "myserver";
$username = "myusername";
$password = "mypass";
$database = "mydb";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);

// Check connection
if (!$conn) {
	echo "Erro na conexão";
      die("Connection failed: " . mysqli_connect_error());
} 

echo "Conexão Ok". "\n";


//collection data 

$sql = 'SELECT id, title, slug, description, price, shipping_cost, product_condition, user_id, category_id FROM products ORDER BY id;';

if (mysqli_query($conn, $sql)) {
    echo "ID captured". "\n";
}

$result = $conn->query($sql);
$row = $result->fetch_assoc();


require "/home/admin/web/mysite.com/public_html/cron/vendor/autoload.php";
//use Vitalybaev\GoogleMerchant\Feed;
//use Vitalybaev\GoogleMerchant\Product;
//use Vitalybaev\GoogleMerchant\Product\Shipping;
//use Vitalybaev\GoogleMerchant\Product\Availability\Availability;

// Create feed object
$feed = new \Vitalybaev\GoogleMerchant\Feed("Mysite", "https://mysite.com", "Mysite descryption");

// Put products to the feed ($products - some data from database for example)
foreach ($result as $product) {

	$chave = $row["id"];
	$titulo = $row["title"];
	$link = $row["slug"];
	$descricao = $row["description"];

	$frete = $row["shipping_cost"];
	if ($frete == 0) {
		$fretefinal = "Frete grátis";
	} else {
		$frete_tam = strlen($frete);
		$fretefinal = substr_replace($frete, ",", $frete_tam-2).substr($frete, $frete_tam-2);
	}
	
	$preco = $row["price"];
	$preco_tam = strlen($preco);
	$preco_final = substr_replace($preco, ",", $preco_tam-2).substr($preco, $preco_tam-2);
	$linkurl ="https://mysite.com/".$link;
	
	// Condiction

	$condi = $row["product_condition"];
	if ($condi == "used") {
		$condi = "Usado";
	   } elseif ($condi == "new") {
		$condi = "Novo";
	   } elseif ($condi == "good") {
		$condi = "Prestacao de servico";
		} elseif ($condi == "satisfactory") {
		$condi = "Animal";
		} elseif ($condi == "very_good") {
		$condi = "Permuta (Troca)";
	} else {
		$condi = "Novo";
	}


	// Image

	$sql_i = 'SELECT DISTINCT image_default FROM images WHERE images.product_id ='.$chave.'';
		if (mysqli_query($conn, $sql_i)) {
			echo "Image Ok". "\n";
		}
		$result_i = $conn->query($sql_i);
		$row_i = $result_i->fetch_assoc();
		$imagem= $row_i["image_default"];


	// Category

	$sql_c = 'SELECT DISTINCT name FROM categories_lang WHERE categories_lang.category_id ='.$chave.' AND lang_id = 2';
		if (mysqli_query($conn, $sql_c)) {
			echo "Category Ok". "\n";
		}
		$result_c = $conn->query($sql_c);
		$row_c = $result_c->fetch_assoc();
		$categoria= $row_c["name"];


	// Brand

	$sql_f = 'SELECT DISTINCT username FROM users WHERE users.id ='.$chave.'';
		if (mysqli_query($conn, $sql_f)) {
			echo "Brand Captured Ok". "\n";
		}
		$result_f = $conn->query($sql_f);
		$row_f = $result_f->fetch_assoc();
		$marca= $row_f["username"];
		$marca_name =$marca. " [xcom products]";



    $item = new \Vitalybaev\GoogleMerchant\Product();
    
    // Set common product properties
    $item->setId($chave);
    $item->setTitle($titulo);
    $item->setDescription($descricao);
    $item->setLink($linkurl);
    $item->setImage($imagem);
    $item->setAvailability("Disponível");
    $item->setPrice("{$product->price} BRL");
    $item->setGoogleCategory($categoria);
    $item->setBrand($marca_name);
    //$item->setGtin($product->barcode);
    $item->setCondition($condi);
    $item->setShipping($fretefinal);

    // Add this product to the feed
    $feed->addProduct($item);
}

// Here we get complete XML of the feed, that we could write to file or send directly
$feedXml = $feed->build();

?>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.