从URL获取价格

时间:2015-02-28 19:41:48

标签: php dom file-get-contents simple-html-dom

我试图使用simple-html-dom从任何给定的网址中获取价格。 我使用的示例代码,运行良好是从这里: http://www.sanwebe.com/2013/06/extract-url-content-like-facebook-with-php-and-jquery

//Include PHP HTML DOM parser (requires PHP 5 +)
include_once("Includes/simple_html_dom.inc.php");

//get URL content
$get_content = file_get_html($get_url); 

获得标题的工作正常:

//Get Page Title 
        foreach($get_content->find('title') as $element) 
        {
            $page_title = $element->plaintext;
        }

然而,在尝试阅读span元素以获得寻找货币符号的价格时,我什么都没得到。

    //Get Price
    foreach($get_content->find('span') as $element) 
    {

        $price = $element->plaintext;

        if (strpos($price, '$') !== FALSE)
            {
                $page_price = $price;
            }

        else { $page_price = '0.00';}
    }

2 个答案:

答案 0 :(得分:0)

不幸的是,这种方式起作用,DOMDocument被延迟并且有时会添加<脚本>内容到textContent ...我不知道如何用“simple_html_dom”来做这件事,但我认为它很容易移植;)(如果它比DOMDocument更聪明,它会让我感到惊讶,但是谁知道。 。)

编辑:更新代码以解决<脚本>使用DOMNode-> textContent

标记问题/错误
<?php 
error_reporting(E_ALL);
$html=file_get_contents("http://rads.stackoverflow.com/amzn/click/B0081IDX84");
$domd=new DOMDocument();
@$domd->loadHTML($html);
$matches=array();
foreach($domd->getElementsByTagName("script") as $node){
//DOMDocument is retarded, and will sometimes add <script> content to 
//textContent, so removing them..
$node->parentNode->removeChild($node);
}


foreach($domd->getElementsByTagName("span") as $node){
    if(strpos($node->textContent, '$') !==false){
        $matches[]=$node->textContent;
    }
}
if(php_sapi_name() === 'cli'){
    var_dump($matches);
    } else {
echo '<pre>';
ob_start();
var_dump($matches);
echo htmlentities(ob_get_clean());
echo '</pre>';
}

您可以在此处查看代码[{3}}

答案 1 :(得分:-1)

strpos()只返回&#34; $&#34;的位置,而不是价格。此外,变量将在每次换行后被覆盖,因此您可能希望在找到正确的值后突破循环。