Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP Web抓取和JSON或数组输出_Php_Arrays_Web Scraping - Fatal编程技术网

PHP Web抓取和JSON或数组输出

PHP Web抓取和JSON或数组输出,php,arrays,web-scraping,Php,Arrays,Web Scraping,我正在尝试用PHP来抓取Amazon,但我不知道我做错了什么。问题是我无法访问我搜集的所有数据。这是我的密码: <?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&r

我正在尝试用PHP来抓取Amazon,但我不知道我做错了什么。问题是我无法访问我搜集的所有数据。这是我的密码:

<?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>";       

  } 
?>

foreach语句循环并输出纯文本,但我希望能够将纯文本传递给变量或数组。问题是,如果我这样做并输出结果,我只会得到纯文本数组的最后一个字符串。我做了很多研究来找出我做错了什么,但我找不到。如果您有任何帮助,我们将不胜感激。以下是我努力实现的目标:

<?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);

?>


第二个代码将输出纯文本的最后一个字符串,即:“RuberMaid午餐盒侧面容器套件,2包,1806176”。我还尝试通过编码和解码纯文本来实现这一点,但没有任何改变。我做错了什么?

不要将数组保持设置为字符串…向数组中添加新元素:

$hold[] = $element->plaintext;        

我觉得PHP可能不是实现这一点的最佳语言…@RoshanBhumbra;谢谢你的评论。你能解释一下为什么吗?Php更适合服务页面,而不是删除页面,而且它有各种各样的怪癖,不利于扩展操作。例如,它有一个执行时间限制,因此您不能像使用其他许多语言一样让它不断地抓取页面。@roshanbhumbra ini_set('max_execution_time',-1);“最长执行时间,以秒为单位。如果设置为零,则没有时间限制。”PHP非常适合抓取。也就是说,amazon非常适合api,而不是抓取,imho;但是,据我们所知,这是一个周末购物项目,在这种情况下,刮擦是有意义的。谢谢你的回复。你为什么把这个问题降级?我已经重新格式化了。我不记得用反推。不管怎样,谢谢你的评论。不是我,我的朋友。谢谢我注意到我没有将$hold声明为数组。你的贡献解决了问题。再次感谢。不用担心,为了好玩,您不必在php中声明数组。你可以去掉它,虽然对其他程序员来说不太清楚,但它的功能是相同的。不管好坏