Devz Studio
Devz Studio

Reputation: 19

How would I be able to get price of Amazon Product in php?

I've looked all over Google, trying to find out how I could find the price of a product using PHP.

I'm looking to get the price from the product URL

I don't want to use the Amazon Web Services as my account was banned and I'm looking for a more simple way of doing it.

I'm not that good with PHP and I've come from Python, I was thinking that you could maybe use something like Regex or match (If those exist in PHP).

Upvotes: 0

Views: 3293

Answers (2)

Cyclonecode
Cyclonecode

Reputation: 30021

You could also use the PHPHtmlParser package.

PHPHtmlParser is a simple, flexible, html parser which allows you to select tags using any css selector, like jQuery. The goal is to assiste in the development of tools which require a quick, easy way to scrap html, whether it's valid or not! This project was original supported by sunra/php-simple-html-dom-parser but the support seems to have stopped so this project is my adaptation of his previous work.

Then you could use it to extract the price doing something like this:

// of course you need to install the package, best done using composer
include 'vendor/autoload.php';

use PHPHtmlParser\Dom;

$dom = new Dom;
// create a Dom object from the desired url
$dom->loadFromUrl("https://www.amazon.com/gp/product/B01LOP8EZC/ref=s9_top_hd_bw_b710gst_g63_i1?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=merchandised-search-1&pf_rd_r=BP4XPK3DA9H3QTJBWM20&pf_rd_t=101&pf_rd_p=2530894322&pf_rd_i=6427871011");
// extract the price from the Dom
$price = $dom->find('#priceblock_ourprice');
print $price->text();

Upvotes: 0

FluxCoder
FluxCoder

Reputation: 1276

Here is some PHP code that will fetch the price, although, if the price is on offer, it will not grab that price, it'll just get the total price of the Amazon Product.

//Grab the contents of the Product page from Amazon
$source = file_get_contents("https://www.amazon.com/dp/B01DFKC2SO");

//Find the Price (Searches using Regex)
preg_match("'<span id=\"priceblock_ourprice\" class=\"a-size-medium a-color-price\">(.*?)</span>'si", $source, $match);

//Check if it was actually found.
if($match){
  //Echo Price if it was indeed found.
  echo $match[1]; 
}

I'm also unsure if it's possible to do this with both .com and the other versions of Amazon, you'll have to do some searching for the correct tags, classes and/or ids.

Edit
As asked for in the comments of this answer, to get the title add this code:

//Find the Title (Searches using Regex)
preg_match("'<span id=\"productTitle\" class=\"a-size-large\">(.*?)</span>'si", $source, $match);
if($match){
  echo $match[1];
}

Upvotes: 1

Related Questions