【问题标题】:php include - how to make variables available where included?php include - 如何使包含的变量可用?
【发布时间】:2011-04-13 08:37:25
【问题描述】:

我正在尝试包含一个文件,该文件正在从各种网站上抓取我的所有数据,但它无法正常工作。这是我的代码。

首先,抓取 php 文件。命名为scrapedata.php

<?php

//Include the Simple HTML DOM to use its functions, used by other following scripts.
//navigate to the content of variable html and save it in price data variable
//get the whole html of the webpage into variable html
include 'simple_html_dom.php';
$html = file_get_html('http://www.play.com/Electronics/Electronics/4-/16230382/New-Apple-iPod-Touch-8GB-4th-Gen/Product.html?');
$price_data = $html->find('h6[id=bodycontent_0_middlecontent_1_ctl00_ctl00_product_ctl00__overview_ctl00__dataControl__price__headerSix',0)->plaintext; 


//Amazon.co.uk scrape
$amazon_html = file_get_html('http://www.amazon.co.uk/New-Apple-iPod-touch-Generation/dp/B0040GIZTI/ref=br_lf_m_1000333483_1_1_img?ie=UTF8&s=electronics&pf_rd_p=229345967&pf_rd_s=center-3&pf_rd_t=1401&pf_rd_i=1000333483&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_r=1ZW9HJW2KN2C2MTRJH60');
$amazon_pd = $amazon_html->find('b[class=priceLarge]',0)->innertext;

libxml_use_internal_errors(true);

$dom = new DOMDocument();
$dom->loadHTML($amazon_html);

$xpath = new DOMXpath($dom);

$expr = "/html/body/div[@id='divsinglecolumnminwidth']/form[@id='handleBuy']/table[3]/tr[3]/td/div/span";
$nodes = $xpath->query($expr); // returns DOMNodeList object
// you can check length property i.e. $nodes->length

//echo $nodes->item(0)->nodeValue; // get first DOMNode object and its value
$stock_data = $nodes->item(0)->nodeValue;

if ( $stock_data == "In stock." ) {
    $stockyesno = "Yes";
} else {
    $stockyesno = "No";
}

//Currys scrape
$currys_html = file_get_html('http://www.currys.co.uk/gbuk/apple-new-ipod-touch-8gb-4th-generation-07677427-pdt.html');
$currys_pd = $currys_html->find('p[class=prd-amount]',0)->plaintext;
$currys_stk = $currys_html->find('/html/body/div/div/div[2]/div/div/div[2]/div/ul[2]/li/span')->plaintext;
//span[class=icon icon-check]',0);

echo $currys_stk;

if ( $currys_stk == "Available for home delivery" ) {
    $currys_stockyesno = "Yes";
} else {
    $currys_stockyesno = "No";
}

//Argos scrape
$argos_html = file_get_html('http://www.argos.co.uk/static/Product/partNumber/9282197/Trail/searchtext%3EIPOD+TOUCH.htm');
$argos_pd = $argos_html->find('span[class=actualprice]',0)->plaintext; 

//Ebuyer scrape
$ebuyer_html = file_get_html('http://www.ebuyer.com/product/237805');
$ebuyer_pd = $ebuyer_html->find('span[class=now]',0)->plaintext;

//PcWorld scrape
$pcworld_html = file_get_html('http://www.pcworld.co.uk/gbuk/apple-new-ipod-touch-8gb-4th-generation-07677427-pdt.html');
$pcworld_pd = $pcworld_html->find('p[class=prd-amount]',0)->plaintext; 
?>

然后是包含它的我的页面,然后它意味着从包含的文件访问变量中的数据。

<?php include 'scrapedata.php';?>     


   <!-- MYSQL DATABASE CODE -->
  <?php
$db_host = 'localhost';
$db_user = 'admin';
$db_pwd = '1admin';

$database = 'stock_checker';
$table = 'price_stock';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

?> 
<!-- MYSQL DATABASE CODE END-->

  //Insert the scraped data into the database.
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('Play.com', '$play_pd' )") 
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price,stock) VALUES('Amazon', '$amazon_pd', '$stockyesno' )") 
or die(mysql_error());
 mysql_query("INSERT INTO price_stock (retailer,price,stock) VALUES('Currys', '$currys_pd', '$currys_stk' )") 
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('Argos', '$argos_pd' )") 
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('eBuyer', '$ebuyer_pd' )") 
or die(mysql_error());
mysql_query("INSERT INTO price_stock (retailer,price) VALUES('PCWorld', '$pcworld_pd' )") 
or die(mysql_error());

?>

<!-- MYSQL DATABASE % TABLE CREATION CODE -->
<?php
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
    die("Query to show fields from table failed");
}

$fields_num = mysql_num_fields($result);


echo "<table width='650px'><tr>";

// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($result);
    echo "<td><b>{$field->name}</b></td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

    echo "</tr>\n";
}
mysql_free_result($result);


?>

我做对了吗?我不知道它们是否会自动被包括在内,还是必须成为 GLOBAL ?

【问题讨论】:

  • 抱歉,我不知何故忘记包含将数据插入数据库的代码。哦!,它现在在那里!
  • 所以包含的文件运行,没有报错,数据也没有出现。抓取的数据是否正在写入数据库?当您检查数据库时,那里有什么?

标签: php mysql web-scraping


【解决方案1】:

这是一个非常糟糕的主意。

你应该使用函数;传递和返回值。在脚本开头包含文件,在需要时调用函数。不要在您包含的文件中放置任何独立(非功能)代码。

(顺便说一句,下一步是 OOP 和自动加载器。)

如果您想知道为什么这是一个非常糟糕的主意:我已经检查了您的代码 5 次(尽管没有深入分析),仍然没有想通找出要在两个文件之间共享的变量。如果我逐行进行,我会找到它,但我不想逐行进行。在 3 个月内,当您更新代码时,您也不会。让我们的工作更轻松。

--

从某种角度来看,对象是函数及其共享状态的集合;所以这是这里的第三步:没有函数 -> 一些函数 -> 函数在类中组合在一起。甚至不知道它是否有任何好处,但是 PHP 有 this 来谈论 OOP。 Autoloading 是 PHP 用来按需加载类的机制,通常可以让您免于包含。

【讨论】:

  • 我犯了一个错误,忘记包含mysql插入代码,这就是变量与包含文件链接的地方。我还在 mysql 代码脚本中移动了 include scrapedata.php。我理解,这可能是一个非常糟糕的主意,但这是一个 uni 项目,而且我对 php 或 mysql 没有任何了解,这只是我收集和整理的内容,我不知道是什么好与不好,或者一个人通常会用什么来完成某事。
  • 抱歉,您能解释一下自动加载器和 OOP 吗? ,我需要研究一下,我不知道:(
  • 我不确定它是否有帮助,但我在一个外部文件中制作然后包含它的原因是因为我需要每 5 分钟使用一次 cron 作业运行它。然后新数据可以覆盖旧记录。
【解决方案2】:

它们不需要显式导入。

试试这个例子:

<?php
// a.php
$myVar = 123;

<?php
// b.php
include 'a.php'
echo isset($myVar)?'Included':'Not included';

与您发布的代码有关:我看不到您将数据添加到数据库的位置。你不也应该这样做吗?

【讨论】:

    【解决方案3】:

    对此类请求使用 DOM 解析是个坏主意。亚马逊发布了一个简单的 API - 在这里阅读:http://aws.amazon.com/de/

    【讨论】:

      【解决方案4】:

      包含文件中的 PHP 变量将以相同的名称出现在主文件中。

      但是在您的代码中,我根本没有看到变量被重用?抓取在变量中生成信息,然后您的主文件读取一个不相关的数据库表。这两个操作需要以某种方式关联。

      【讨论】:

      • 抱歉,我忘了包含从外部 php 文件调用变量的 mysql 代码。
      猜你喜欢
      • 2017-09-09
      • 2016-03-05
      • 2023-03-31
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 2014-10-07
      相关资源
      最近更新 更多