Skip to content

Instantly share code, notes, and snippets.

@dhaupin
Last active September 12, 2021 09:26
Show Gist options
  • Save dhaupin/b74a0c514a91bacff0d3 to your computer and use it in GitHub Desktop.
Save dhaupin/b74a0c514a91bacff0d3 to your computer and use it in GitHub Desktop.
Function - Parse Google merchant center shopping categories into Array or JSON - works with search url param or direct category_id argument
<?php
// This is part of a product class, this function shalt also be available via route with optional ?search= param
// $this->request->get is platform specific, change it to whatever your request wrapper uses
public function googlecats($cat_ids = false) {
// default format
$json = true;
$pool = $mitigate = $output = array();
$pool = file('http://www.google.com/basepages/producttype/taxonomy-with-ids.en-US.txt', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
$version = array_shift($pool);
foreach ($pool as $row) {
list($id, $cat) = explode(' - ', $row);
$mitigate[$id] = $cat;
}
// done with $pool
unset($pool);
if (isset($this->request->get['search'])) {
// check for ?search= query and make placeholder for space
$search = str_replace('%20', '~~~', (string)$this->request->get['search']);
foreach ($mitigate as $key => $value) {
str_replace(' ', '~~~', $value);
if ((stripos($key, $search) !== false) || (stripos($value, $search) !== false)) {
// as 1 associative array
// $output[$key] = $value;
// as double key => value array
$output[] = array('g_cid' => $key, 'g_cat' => $value);
}
}
} elseif (isset($cat_ids)) {
// check for $cat_ids array
foreach ($cat_ids as $cat_id) {
foreach ($mitigate as $key => $value) {
if ($key == $cat_id) {
// as 1 associative array
// $output[$key] = $value;
// as double key => value array
$output[] = array('g_cid' => $key, 'g_cat' => $value);
}
}
}
// output array instead
$json = false;
} else {
$output = $mitigate;
}
// done with $mitigate
unset($mitigate);
// return output as json or array
if (empty($output)) {
return false;
} elseif ($json) {
echo json_encode($output);
} else {
return $output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment