公司项目开发遇到一个需求,需要根据用户填写的企业名称获取公开的企业信息实现自动填写,搜索了一圈没有找到合适的 API ,无奈便打起了 水滴信用 的主意 ...

<?php
function GetHtmlSourceCode($url) {
if (!preg_match('/http:\/\/.*/i', $url)) return false;
$ch = curl_init();
$timeout = 10;
if (!curl_setopt ($ch, CURLOPT_URL, $url)) return false;
if (!curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1)) return false;
if (!curl_setopt ($ch, CURLOPT_HEADER, true)) return false;
if (!curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout)) return false;
$html = curl_exec($ch);
$info = curl_getinfo($ch);
$header = substr($html, 0, $info['header_size']);
$html = substr($html, $info['header_size']);
if (strpos($header, 'gzip')) {
$html = gzdecode($html);
}
if (!strpos($header, 'utf-8')) {
$html = mb_convert_encoding($html, 'utf-8', 'utf-8,gb2312,gbk,big5');
}
return $html;
}
function GetUrlByKeyword($html, $keyword) {
$pattern = "/<a[^>]*companyname=\"{$keyword}\"[^>]*>/isU";
preg_match($pattern, $html, $matches);
$pattern = '/href="(.*)"/isU';
preg_match($pattern, $matches[0], $matches);
if (!is_null($matches[1])) {
$url = 'http://shuidi.cn' . $matches[1];
return $url;
}
return false;
}
function GetInfoBySourceCode($html) {
$info = array();
$list = array(
'工商注册号' => 'registcode',
'登记状态' => 'status',
'法定代表人' => 'legal',
'注册资本' => 'capital',
'企业信用代码' => 'creditcode',
'成立时间' => 'established',
'登记机关' => 'authority',
'核准日期' => 'approved',
'营业期限' => 'period',
'企业类型' => 'corptype',
'所在省份' => 'province',
'企业地址' => 'address',
'经营范围' => 'scope',
);
foreach ($list as $key => $value) {
//$pattern = "/{$key}<\/td>[\s\S]*<td>(.*)<\/td>/isU";
$pattern = "/{$key}<\/td>[\s\S]*<td[^>]*>(.*)<\/td>/isU";
preg_match($pattern, $html, $matches);
if (is_null($matches[1])) {
return false;
} elseif ($key == '法定代表人') {
preg_match('/<a[^>]*>(.*)<\/a>/isU', $matches[1], $matches);
} elseif ($key == '经营范围') {
preg_match('/<div[^>]*class="overflow"[^>]*>(.*)<\/div>/isU', $matches[1], $matches);
}
$info[$value] = $matches[1];
}
return $info;
}
function GetCorpInfo() {
$data = array(
'code' => 500,
'msg' => 'Unknown Error'
);
if (isset($_POST['corp'])) {
$keyword = $_POST['corp'];
$url = 'http://shuidi.cn/pc-search?key='. $keyword;
$html = GetHtmlSourceCode($url);
if ($html) {
$url = GetUrlByKeyword($html, $keyword);
if ($url) {
$html = GetHtmlSourceCode($url);
if ($html) {
$info = GetInfoBySourceCode($html);
if ($info) {
$data = array(
'code' => 0,
'msg' => 'ok',
'info' => $info
);
} else {
$data = array(
'code' => 101,
'msg' => 'Some Info is Missing due to Webpage revision'
);
}
} else {
$data = array(
'code' => 102,
'msg' => 'Can not Open this URL'
);
}
} else {
$data = array(
'code' => 103,
'msg' => 'Incorrect Company Name'
);
}
} else {
$data = array(
'code' => 104,
'msg' => 'Can not Open this URL'
);
}
}
return $data;
}
本文标题:水滴信用 API
版权声明:本文使用「署名-非商业性使用-相同方式共享」创作共享协议,转载或使用请遵守署名协议。