我在这里尝试REST API:https://www.semrush.com/api-analytics/,特别是有机结果,但无论我尝试过什么,我似乎无法操纵数据。谁能告诉我怎么做?我尝试过SimpleXML,JSON,甚至通过explode()分解响应,但我必须遗漏一些东西,因为我所能做的就是将结果推送到数组的开头而不是实际分解它。
这是我目前的代码:
$url = "http://api.semrush.com/?type=phrase_organic&key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&display_limit=10&export_columns=Dn,Ur&phrase=seo&database=us";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
结果是:
string 'Domain;Url
site-analyzer.com;https://www.site-analyzer.com/
woorank.com;https://www.woorank.com/
hubspot.com;http://blog.hubspot.com/blog/tabid/6307/bid/33164/6-SEO-Tools-to-Analyze-Your-Site-Like-Google-Does.aspx
seoworkers.com;http://www.seoworkers.com/tools/analyzer.html
seositecheckup.com;http://seositecheckup.com/
site-seo-analysis.com;http://www.site-seo-analysis.com/
webseoanalytics.com;http://www.webseoanalytics.com/free/seo-tools/web-seo-analysis.php
seocentro.com;http://www.seocentro.com/t'... (length=665)
有没有一种简单的方法来解决这个问题,以便我可以操纵或重新格式化响应?
答案 0 :(得分:0)
好吧,我们可以按空格" "
,然后按;
$response = explode(" ", trim(str_replace("Domain;Url", "", $response)));
$readableResponse = [];
foreach($response as $r)
{
$e = explode(";", $r);
$readableResponse[$e[0]] = $e[1];
}
print_r($readableResponse);
IE中。 Live on phpsandbox
[searchengineland.com] => http://searchengineland.com/guide/what-is-seo
[wikipedia.org] => https://en.wikipedia.org/wiki/Search_engine_optimization
....
答案 1 :(得分:0)
您需要正确地展开新行字符才能进入csv
结构,然后将其解析为csv
foreach(preg_split("/((\r?\n)|(\r\n?))/", $response) as $key=>$line){
if ($key!=0) {
list($domain,$url) = str_getcsv($line,';');
print 'Domain: ' . $domain . ', URL: ' . $url . PHP_EOL;
}
}
使用来自https://www.semrush.com/api-analytics/#phrase_organic的示例回复,
以上将输出
Domain: wikipedia.org, URL: http://en.wikipedia.org/wiki/Search_engine_optimization
Domain: searchengineland.com, URL: http://searchengineland.com/guide/what-is-seo
Domain: moz.com, URL: http://moz.com/beginners-guide-to-seo
if
语句用于过滤掉第一行,即csv标题。