首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP解析外部站点

PHP解析外部站点
EN

Stack Overflow用户
提问于 2013-07-25 12:07:51
回答 1查看 1.8K关注 0票数 1

我在解析外部url以获取数据方面没有任何经验,但今天我尝试了一些实验:

代码语言:javascript
复制
$str1 = file_get_contents('http://www.indiegogo.com/projects/ubuntu-edge');
$test1 = strstr($str1, "amount medium clearfix");
$parts = explode(">",$test1);
$parts2 = vsprintf("%s", $parts[1]);

$str2 = file_get_contents('http://www.indiegogo.com/projects/ubuntu-edge');
$test2 = strstr($str2, "money-raised goal");
$test3 = str_ireplace("money-raised goal", "", "$test2");
$test4 = str_ireplace("\"", "", "$test3");
$test5 = str_ireplace(">", "", "$test4");
$test6 = substr($test5, 0, 29);
$test7 = explode("Raised of", $test6);
$test8 = vsprintf("%s", $test7[1]);

使用以下代码尝试代码:

print_r($parts2);然后是print_r($test8);,然后是echo "$parts2 - $test8";

因为现在Ubuntu运动很受欢迎,所以我试着从网站上获得这两个领域(只是作为一个实验),但没有成功。它抓住了两个字段,但我不能把这两个变量都放在同一个变量中。输出是或$parts2,或$parts2包含test8的值,或仅包含$test8。

我做错了什么,为什么?还有一个更简单的方法来做我想做的事,没有这么多的代码吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-25 13:12:25

它抓住了两个字段,但我不能把这两个变量都放在同一个变量中。

不知道你在说什么。

还有一个更简单的方法来做我想做的事,没有这么多的代码吗?

没有这么多密码?不是的。更灵活(可能)有效?是。

试试这个,根据你的喜好量身定做。

代码语言:javascript
复制
<?php
$page = file_get_contents('http://www.indiegogo.com/projects/ubuntu-edge');

$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($page);

$finder = new DomXPath($doc);

// find class="money-raised"
$nodes = $finder->query("//*[contains(@class, 'money-raised')]");

// get the children of the first match  (class="money-raised")
$raised_children = $nodes->item(0)->childNodes;

// get the children of the second match (class="money-raised goal")
$goal_children = $nodes->item(1)->childNodes;

// get the amount value
$money_earned = $raised_children->item(1)->nodeValue;

// get the amount value
preg_match('/\$[\d,]+/', $goal_children->item(0)->nodeValue, $m);
$money_earned_goal = $m[0];


echo "Money earned: $money_earned\n";
echo "Goal: $money_earned_goal\n";

?>

这有11行没有echos的代码(与12行相比),但只调用其他站点一次。抓取网站是一项有点牵扯的任务。这段代码从这个精确的页面中获取您想要的值。

如果您想刮站点,我强烈建议您学习使用DOMDocumentDOMXPath。有很多东西要学,但值得努力。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17857598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档