在PHP之前加载并显示HTML

时间:2014-10-16 03:14:47

标签: php html xpath web-scraping domdocument

我有2个php文件(index.php和lelong.php)。我试图在index.php(表)中首先加载html并在第二列上显示单词(Calculating ...),而lelong.php在输出之前从网站中提取数据。

有办法吗?我听说过使用JS或AJAX,但不知道该怎么做。

的index.php

<!DOCTYPE html>
<html>
<head>
<?php include 'lelong.php'; ?>
</head>

<body>
<table border ="1" style = "width:50%">
    <tr>
        <td>E-Commerce Website</td>
         <td>No. of Products </td>
    </tr>
    <tr>
        <td>Lelong</a></td>
        <td><?php echo $lelong; ?></td>
    </tr>
</table>    

<body>

lelong.php

<?php
$grep = new DoMDocument();
@$grep->loadHTMLFile("http://www.lelong.com.my/Auc/List/BrowseAll.asp");
$finder = new DomXPath($grep);
$class = "CatLevel1";
$nodes = $finder->query("//*[contains(@class, '$class')]");

$total_L = 0;
foreach ($nodes as $node) {
    $span = $node->childNodes;
    $search = array(0,1,2,3,4,5,6,7,8,9);
    $number = str_replace($search, '', $span->item(1)->nodeValue);
    $number = preg_replace("/[^0-9]/", '', $span->item(1)->nodeValue);

    $total_L += (int) $number;  
}   
    $lelong = number_format( $total_L , 0 , '.' , ',' );

?>

由于

2 个答案:

答案 0 :(得分:1)

假设lelong.php已经正常工作,是的,您可以使用ajax来获得结果:

基本示例:

所以在你的HTML中:

<table border ="1" style = "width:50%">
    <tr>
        <td>E-Commerce Website</td>
         <td>No. of Products </td>
    </tr>
    <tr>
        <td>Lelong</a></td>
        <td class="result_data">Calculating ...</td><!-- initial content. Loading ... -->
    </tr>
</table>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function(){

    // use ajax, call the PHP
    $.ajax({
        url: 'lelong.php', // path of lelong
        success: function(response){
            $('.result_data').text(response);
        }
    })
});
</script>

然后在你的PHP中:

<?php

$grep = new DoMDocument();
@$grep->loadHTMLFile("http://www.lelong.com.my/Auc/List/BrowseAll.asp");
$finder = new DomXPath($grep);
$class = "CatLevel1";
$nodes = $finder->query("//*[contains(@class, '$class')]");

$total_L = 0;
foreach ($nodes as $node) {
    $span = $node->childNodes;
    $search = array(0,1,2,3,4,5,6,7,8,9);
    $number = str_replace($search, '', $span->item(1)->nodeValue);
    $number = preg_replace("/[^0-9]/", '', $span->item(1)->nodeValue);

    $total_L += (int) $number;  
}

$lelong = number_format( $total_L , 0 , '.' , ',' );

echo $lelong; // output lelong
exit;

?>

前面的效果是你的控制。你可以使用插件。

答案 1 :(得分:0)

lelong.php页面中,最后添加一行echo $lelong;

index.php中,删除<?php include 'lelong.php'; ?>,然后导入JQuery库。例如<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

<td><?php echo $lelong; ?></td>替换为<td id='lelong'>Calculating...</td>

添加jquery代码<script>$('#lelong').load('lelong.php');</script>

首先学习jQuery会更好。