Я новичок в PHP
программировании. У меня есть этот скрипт, в котором я пытаюсь получить строку несколько раз, каждый раз с различными данными для входа в систему, с внешнего сайта . Я использую PHP
, cURL
, DOM
и XPath
. Дело в том, что мой код работает, только если я не использую конструкцию foreach
для зацикливания всей операции. Но я не знаю, как еще я мог бы повторить эту операцию, изменяя данные время от времени.
Ситуация такова: я только что вошел в систему, и теперь сайт просит меня заполнить еще два поля, которыеНеобходимо перейти на следующую страницу, где я могу получить строку, которая мне нужна. Следующая часть кода содержится в блоке if
.
// A function to automatically select the form fields:
function form_fields($xpath, $query) {
$inputs = $xpath->query($query);
$fields = array();
foreach ($inputs as $input) {
$key = $input->attributes->getNamedItem('name')->nodeValue;
$type = $input->nodeName;
$value = $input->attributes->getNamedItem('value')->nodeValue;
$fields[$key] = $value;
}
return $fields;
}
// Executing the XPath queries to fill the fields:
$opzutenza = 'incarichi';
$action = $xpath->query("//form[@name='fm_$opzutenza']")->item(0)->attributes->getNamedItem('action')->nodeValue;
curl_setopt($ch, CURLOPT_URL, $action);
$fields = form_fields($xpath, "//form[@name='fm_$opzutenza']/input");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
$html = curl_exec($ch);
$dom = new DomDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
// The strings that I need to get depend on each value contained in this select element:
$options = $xpath->query("//select[@name='sceltaincarico']/option");
$partiteiva = array();
foreach($options as $option){
$partiteiva[] = $option->nodeValue;
unset($partiteiva[0]);
}
} // -----------> END OF 'IF' BLOCK
$queriesNA = array();
foreach ($partiteiva as $piv) {
$queryNA = ".//select[@name='sceltaincarico']/option[text()='$piv']";
$queriesNA[] = $queryNA;
}
// And this is the problematic loop:
foreach($queriesNA as $querypiv){
$form = $xpath->query("//form[@name='fm_scelta_tipo_incarico']")->item(0);
$action = $form->attributes->getNamedItem('action')->nodeValue;
@$option = $xpath->query($querypiv, $form);
curl_setopt($ch, CURLOPT_URL, $action);
$fields = [
'sceltaincarico' => $option->item(0)->attributes->getNamedItem('value')->nodeValue,
'tipoincaricante' => 'incDiretto'
];
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields)); // ----> Filling the last field
curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'https://website.com/dp/api');
curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'https://website.com/cons/cons-services/sc/tokenB2BCookie/get');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
$http = curl_exec($ch);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_NOBODY, false);
function parse_headers($http) {
$headers = explode("\r\n", $http);
$hdrs = array();
foreach($headers as $h) {
@list($k, $v) = explode(':', $h);
$hdrs[trim($k)] = trim($v);
}
return $hdrs;
}
$hdrs = parse_headers($http);
$tokens = array(
"x-token: ".$hdrs['x-token'],
"x-b2bcookie: ".$hdrs['x-b2bcookie']
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $tokens);
curl_setopt($ch, CURLOPT_URL, "https://website.com/cons/cons-services/rs/disclaimer/accetta"); // Accepting the disclaimer...
curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, "https://website.com/portale/web/guest/home");
$html = curl_exec($ch); // Finally got to the page that I need
$dom = new DomDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
// Selecting the string:
$string = $xpath->query("//div[@class='informativa']/strong[2]");
$nomeazienda = array();
foreach ($string as $str) {
$nomeazienda[] = $str->childNodes->item(0)->nodeValue;
}
// Going back to the initial page so the loop can start again from the beginning:
$piva_page = 'https://website.com/portale/scelta-utenza-lavoro?....';
curl_setopt($ch, CURLOPT_URL, $piva_page);
$html = curl_exec($ch);
$dom = new DomDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
}
curl_close($ch);
Это сообщения об ошибках:
Примечание: попытка получить свойство 'атрибуты' неobject ...
Неустранимая ошибка: Uncaught Ошибка: вызов функции-члена getNamedItem () для null ...
Ошибка: вызов функции-члена getNamedItem () для null ...
Функция getNamedItem()
является первой сразу после неисправного цикла, как и «атрибуты».