#php #api #curl #post #http-post
#php #API #curl #Публикация #http-post
Вопрос:
Я пытаюсь использовать http://validator.w3.org/nu/
API для прямого ввода через метод POST.
https://github.com/validator/validator/wiki/Service-»-Input-»-textarea
Это то, что я пробовал, но безуспешно
class frontend {
public static function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
$user_agent = self::random_user_agent();
//var_dump($user_agent);
curl_setopt($ch,CURLOPT_USERAGENT,$user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if (strpos($url, 'https') !== false) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
$domain = 'yahoo.com';
$url = 'https://'.$domain;
$html = frontend::file_get_contents_curl($url);
libxml_use_internal_errors(true);
$doc = new DOMDocument;
$doc->loadHTML($html);
$html_file_output = $domain.'.html';
$dir = $_SERVER['DOCUMENT_ROOT'].'/tmp/';
if(!file_exists($dir)) {
mkdir($dir);
}
$file_path = $dir.$html_file_output;
$doc->saveHTMLFile($file_path);
var_dump($file_path); // the filepath where the file is saved /www.domain.com/tmp/html_file.html
$url_validator = 'http://validator.w3.org/nu/';
$query = [
'out' => 'json',
'content' => $html // the HTML resulting from $url variable %0....
//'content' => $file_path tried also => /www.domain.com/tmp/the_file.html
];
$query_string = http_build_query($query);
var_dump($query_string); // returns string 'out=jsonamp;content=doctype html....' or 'out=jsonamp;content=F:/SERVER/www/www.domain.com/tmp/yahoo.com.html'
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$str_html = curl_exec($ch);
curl_close($ch);
$data = json_decode($str_html);
var_dump($data); // returns null
unlink($file_path);
Ответ №1:
во-первых, API «прямого ввода» принимает запросы POST только в multipart/form-data
-формате, но когда вы запускаете его через http_build_query()
, вы конвертируете его в application/x-www-form-urlencoded
-формат, который этот api не понимает. (укажите CURLOPT_POSTFIELDS массив, и он автоматически преобразуется в multipart/form-data
)
во-вторых, этот API блокирует запросы, в которых отсутствует User-Agent
заголовок, а у libcurl нет пользовательского интерфейса по умолчанию (у curl в программе cli есть, а у libcurl нет), поэтому вы должны указать его самостоятельно, но у вас его нет.
… исправляем эти 2 и добавляем простой синтаксический анализ сообщений об ошибках,
<?php
$ch=curl_init();
$html=<<<'HTML'
<!DOCTYPE html>
<html lang="">
<head>
<title>Test</title>
</head><ERRamp;OR
<body>
<p></p>
</body>
</html>
HTML;
curl_setopt_array($ch,array(
CURLOPT_URL=>'http://validator.w3.org/nu/',
CURLOPT_ENCODING=>'',
CURLOPT_USERAGENT=>'PHP/'.PHP_VERSION.' libcurl/'.(curl_version()['version']),
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>array(
'showsource'=>'yes',
'content'=>$html
),
CURLOPT_RETURNTRANSFER=>1,
));
$html=curl_exec($ch);
curl_close($ch);
$parsed=array();
$domd=@DOMDocument::loadHTML($html);
$xp=new DOMXPath($domd);
$res=$domd->getElementById("results");
foreach($xp->query("//*[@class='error']",$res) as $message){
$parsed['errors'][]=trim($message->textContent);
}
var_dump($html);
var_dump($parsed);
С принтами:
array(1) {
["errors"]=>
array(4) {
[0]=>
string(156) "Error: Saw < when expecting an attribute name. Probable cause: Missing > immediately before.At line 6, column 1</head><ERRamp;ORâ©<body>â©<p></p>â©"
[1]=>
string(254) "Error: Element erramp;or not allowed as child of element body in this context. (Suppressing further errors from this subtree.)From line 5, column 8; to line 6, column 6e>â©</head><ERRamp;ORâ©<body>â©<p></Content model for element body:Flow content."
[2]=>
string(144) "Error: End tag for body seen, but there were unclosed elements.From line 8, column 1; to line 8, column 7>â©<p></p>â©</body>â©</htm"
[3]=>
string(118) "Error: Unclosed element erramp;or.From line 5, column 8; to line 6, column 6e>â©</head><ERRamp;ORâ©<body>â©<p></"
}
}
… и проблемы с юникодом возникают из-за того, что кодировка DOMDocument по умолчанию равна.. idk, не-utf8, afaik нет хорошего способа установить кодировку по умолчанию с помощью DOMDocument, но вы можете обойти это, выполнив
$domd=@DOMDocument::loadHTML('<?xml encoding="UTF-8">'.$html);
что заставляет его печатать:
array(1) {
["errors"]=>
array(4) {
[0]=>
string(147) "Error: Saw < when expecting an attribute name. Probable cause: Missing > immediately before.At line 6, column 1</head><ERRamp;OR↩<body>↩<p></p>↩"
[1]=>
string(245) "Error: Element erramp;or not allowed as child of element body in this context. (Suppressing further errors from this subtree.)From line 5, column 8; to line 6, column 6e>↩</head><ERRamp;OR↩<body>↩<p></Content model for element body:Flow content."
[2]=>
string(135) "Error: End tag for body seen, but there were unclosed elements.From line 8, column 1; to line 8, column 7>↩<p></p>↩</body>↩</htm"
[3]=>
string(109) "Error: Unclosed element erramp;or.From line 5, column 8; to line 6, column 6e>↩</head><ERRamp;OR↩<body>↩<p></"
}
}
… который лучше, но все еще содержит стрелки, используемые на веб-странице, которые можно удалить с помощью
foreach($xp->query("//*[@class='lf']") as $remove){
$remove->parentNode->removeChild($remove);
}
что заставляет его печатать:
array(1) {
["errors"]=>
array(4) {
[0]=>
string(138) "Error: Saw < when expecting an attribute name. Probable cause: Missing > immediately before.At line 6, column 1</head><ERRamp;OR<body><p></p>"
[1]=>
string(236) "Error: Element erramp;or not allowed as child of element body in this context. (Suppressing further errors from this subtree.)From line 5, column 8; to line 6, column 6e></head><ERRamp;OR<body><p></Content model for element body:Flow content."
[2]=>
string(126) "Error: End tag for body seen, but there were unclosed elements.From line 8, column 1; to line 8, column 7><p></p></body></htm"
[3]=>
string(100) "Error: Unclosed element erramp;or.From line 5, column 8; to line 6, column 6e></head><ERRamp;OR<body><p></"
}
}