Skip to content

Instantly share code, notes, and snippets.

@elabx

elabx/import.php Secret

Created April 16, 2019 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elabx/ba4879fe36ca9430f8d614aaee52fc5a to your computer and use it in GitHub Desktop.
Save elabx/ba4879fe36ca9430f8d614aaee52fc5a to your computer and use it in GitHub Desktop.
<?php
require 'vendor/autoload.php';
use League\Csv\Reader;
//use Intervention\Image\ImageManagerStatic as Image;
// function searchProducts($products, $sku){
// $foundVariants = array();
// foreach($products as $product){
// foreach($product->variants as $variant){
// if($variant->sku == $sku){
// $foundVariants[] = $variant->id;
// }
// }
// }
// //echo json_encode($foundVariants, JSON_PRETTY_PRINT);
// return $foundVariants;
// }
//Image::configure(array('driver' => 'imagick'));
//Image::configure(array('driver' => 'imagick'));
function getImages($product){
// $marca = trim(strtoupper($product["Marca"]));
// $codigo = trim($product["Código"]);
// //echo realpath("./imagenes");
// $path = "./ProductosAbrilFotos/{$marca}/{$codigo}";
// echo print_r($path . PHP_EOL, true);
// $path = realpath($path);
// echo print_r($path . PHP_EOL, true);
// $selected = [];
//$html = file_get_contents("https://www.monicaxerrano.mx/products/{$product['Slug']}");
$dom = new DOMDocument;
$dom->loadHTMLFile("https://www.monicaxerrano.mx/products/{$product['Slug']}");
$dom->preserveWhiteSpace = false;
//$images = $dom->getElementsByTagName('');
$galleryElement = $dom->getElementById('main-image');
$images = $galleryElement->getElementsByTagName("img");
echo print_r($images, true);
$hrefs = array();
foreach ($images as $image) {
$href[] = $image->getAttribute('src');
}
echo print_r($href, true);
// preg_match_all('/([-a-z0-9_\/:.]+\.(jpg|jpeg|png))/i', $html, $matches);
// echo print_r($matches, true);
$selected = [];
foreach($href as $source){
try {
$fileName = explode("/", parse_url($source)['path'])[0];
$filePath = "./images/$fileName";
$file = file_get_contents($source);
// $ext = pathinfo($filePath, PATHINFO_EXTENSION);
// $name = pathinfo($filePath, PATHINFO_FILENAME);
// Create a new SimpleImage object
$image = new \claviska\SimpleImage();
$image = $image->fromString($file)->toString("image/jpeg");
$selected[]["attachment"] = base64_encode($image);
} catch(Exception $err) {
// Handle errors
echo $err->getMessage();
}
// try{
// $file = file_put_contents( "./images",file_get_contents($source) );
// $ext = pathinfo($file, PATHINFO_EXTENSION);
// $name = pathinfo($file, PATHINFO_FILENAME);
// if($ext == "gif"){
// $image = imagecreatefromgif($file);
// imagejpeg($image, $output_path_with_jpg_extension);
// }
// // if($source){
// // } else{
// // }
// $selected[]["attachment"] = base64_encode();
// }catch(Exception $e){
// echo $e;
// }
}
// echo print_r($selected, true);
return $selected;
}
function setDescription($description){
$description = explode(PHP_EOL,$description);
$html = "";
foreach($description as $text){
$html .= "<p>". $text . "</p>";
}
echo $html;
return $html;
}
function updateVariantPrice($client, $variantId, $product){
$data = ['variant' =>
['price' => (filter_var($product["Precio"], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION) / 100),
'sku' => filter_var($product["SKU"]),
'compare_at_price' => $product['Precio de comparación'] / 100
]
];
echo print_r($data, true);
echo print_r($data, true);
//$data["variant"]["sku"] = $product['Código'];
$result = $client->put('variants/' . $variantId, $data);
//echo json_encode($result, JSON_PRETTY_PRINT);
}
function addProduct($client, $product){
$data = ['product' =>
['title' => $product["Nombre"],
//'images' => getImages($product),
'vendor' => "Mónica Xerrano",
//'product_type' => "Bolsa",
'body_html' => $product["Descripción"],
'published' => $product["Visible"],
'tags'=> str_replace(";",",", $product["Categorías"])
]];
if($product['Visible'] == "TRUE"){
$data['product']['images'] = getImages($product);
}
//echo rint_r($data);
$createdProduct = $client->post('products', $data);
//echo print_r($createdProduct, true);
$variantId = $createdProduct->product->variants[0]->id;
//echo $variantId;
updateVariantPrice($client, $variantId, $product);
}
$SHOPIFY_SHOP_DOMAIN = "store.myshopify.com";
$SHOPIFY_API_KEY = "****";
$SHOPIFY_PASSWORD = "***";
$SHOPIFY_SHARED_SECRET = "***";
$client = new Shopify\PrivateApp($SHOPIFY_SHOP_DOMAIN, $SHOPIFY_API_KEY, $SHOPIFY_PASSWORD, $SHOPIFY_SHARED_SECRET);
$result = $client->get('shop');
header('Content-Type: application/json');
$products = $client->getProducts();
//echo print_r($products, true);
foreach($products as $product){
$r = $client->deleteProduct($product->id);
echo "Deleting ... .. ";
}
//load the CSV document from a file path
$csvFiles = [
"Productos" => "./Monica Zerrano - products-(2018-09-28).csv"
];
foreach($csvFiles as $type => $productCsv){
$csv = Reader::createFromPath($productCsv);
$csv->setDelimiter(',');
$csv->setHeaderOffset(0);
$header = $csv->getHeader(); //returns the CSV header record
$records = $csv->getRecords(); //returns all the CSV records as an Iterator object
foreach($records as $i => $product){
//echo print_r($product, true) . PHP_EOL;
echo print_r($product["Nombre"], true) . PHP_EOL;
echo print_r($product["Visible"], true) . PHP_EOL;
//if($product['Visible'] == "true"){
$variantIdOfProduct = addProduct($client, $product);
//}
// $variantsIdsFound = searchProducts($products, $product["sku"]);
// foreach($variantsIdsFound as $variantId){
// echo print_r($variantId . "\n");
// updateVariant($client, $variantId, intval($product["qty"]));
// }
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment