Kelly Kelly - 16 days ago 5
PHP Question

PHP Web Scraping And JSON or Array Output

I'm experimenting scraping Amazon with PHP but I don't know what I am doing wrong. The problem is that I can't access all the data I scraped. Here is my code:

<?php

$url = 'https://www.amazon.com/s/ref=nb_sb_ss_c_1_9?url=search-alias%3Daps&field-keywords=most+sold+items+on+amazon&sprefix=most+sold%2Caps%2C435&crid=348CE8G406XVG&rh=i%3Aaps%2Ck%3Amost+sold+items+on+amazon';

$html = file_get_html($url);

foreach ($html->find('h2[class=a-size-medium]') as $element) {

echo "<li>" .$element->plaintext."</li><br>";

}
?>


The foreach statement loops through and output the plain text but I want to be able to pass the plain text to a variable or array. The problem is that if I do that and output the result, I only get the last string of the plain text array. I have done lots of research to find what I'm doing wrong but I can't find it. Please any help will be appreciated. Here is what I'm trying to achieve:

<?php
$url = 'https://www.amazon.com/s/ref=nb_sb_ss_c_1_9?url=search-alias%3Daps&field-keywords=most+sold+items+on+amazon&sprefix=most+sold%2Caps%2C435&crid=348CE8G406XVG&rh=i%3Aaps%2Ck%3Amost+sold+items+on+amazon';
$hold = array();
$html = file_get_html($url);

foreach ($html->find('h2[class=a-size-medium]') as $element) {

$hold = $element->plaintext;

}
print_r($hold);

?>


The second code will output the last string of the plain text which is: "Rubbermaid LunchBlox Side Container Kit, 2-Pack, 1806176". I also tried achieving this by encoding and decoding the plain text but nothing changed. What am I doing wrong?

Answer

Instead of setting the array hold to a string...add new elements to the array:

$hold[] = $element->plaintext;