Во-первых, API "прямого ввода" принимает POST-запросы только в формате multipart/form-data
, но когда вы запускаете его через http_build_query()
, вы конвертируете его в application/x-www-form-urlencoded
-формат, который этот API не понимает. , (дать CURLOPT_POSTFIELDS массив, и он автоматически преобразуется в multipart/form-data
)
во-вторых, этот API блокирует запросы, в которых отсутствует заголовок User-Agent
, а libcurl не имеет UA по умолчанию (curl в программе cli, но libcurl - нет), поэтому вы должны предоставить его самостоятельно, но это не так.
... исправление этих 2 и добавление простого разбора сообщения об ошибке,
<?php
$ch=curl_init();
$html=<<<'HTML'
<!DOCTYPE html>
<html lang="">
<head>
<title>Test</title>
</head><ERR&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><ERR&ORâ©<body>â©<p></p>â©"
[1]=>
string(254) "Error: Element err&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><ERR&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 err&or.From line 5, column 8; to line 6, column 6e>â©</head><ERR&ORâ©<body>â©<p></"
}
}
... и проблемы с юникодом возникают из-за того, что набор символов по умолчанию в DOMDocument является .. idk, not-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><ERR&OR↩<body>↩<p></p>↩"
[1]=>
string(245) "Error: Element err&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><ERR&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 err&or.From line 5, column 8; to line 6, column 6e>↩</head><ERR&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><ERR&OR<body><p></p>"
[1]=>
string(236) "Error: Element err&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><ERR&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 err&or.From line 5, column 8; to line 6, column 6e></head><ERR&OR<body><p></"
}
}