Take an input value by name

Asked

Viewed 423 times

0

Hello,

I have the following function:

function capturar($string, $start, $end) {
    $str = explode($start, $string);
    $str = explode($end, $str[1]);
    return $str[0];
}

I use it with Curl, to get the value of an input.

Example of use:

$pagina = curl("http://example.com");
$texto = capturar($pagina, 'name="texto"', '"');
echo $texto;

Then in the case, PHP would return the input value or any tag that has the name of texto, so far so good, but the page that Curl accesses has the following input:

<input value="João Lima" name="texto" id="texto"/>

How would I get the value of the input in this order?

Thanks in advance.


Current code I’m using:

<?php
function curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_COOKIESESSION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, getcwd().'/test.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, getcwd().'/test.txt');
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
$array = [];
preg_match('/value="([^"]+)"/e', curl('http://example.com'), $array);
var_dump($array);
echo '<br><br><br><br>'.curl('http://example.com');

This page has other inputs, but has an input with the value of 11.5, 12, 12.5.

2 answers

1

I think the ideal is to use your own Xpath, native to PHP.


In this case it uses the //input[@name="texto"] that to get the input which contains the attribute of name of texto.

That way I’d be like:

$html = curl("http://example.com");

$DOM = new DOMDocument;
$DOM->loadHTML($html);
$XPath = new DomXPath($DOM);

// Procura pelo elemento:
$inputs = $XPath->query('//input[@name="texto"]');

// Para cada //input[@name="texto"] (já que pode haver mais de um) e exibe o `value`.
foreach($inputs as $_ => $input){
    echo $input->getAttribute('value');
}

0

If it is a single input, this should solve:

$conteudo = '<input value="João Lima" name="texto" id="texto"/>';
$array = [];
preg_match('/value="([^"]+)"/e',$conteudo,$array);
var_dump($array);

This is just one example, it should be adapted. The $conteudo should be the return of your request made with CURL.

  • 1

    And when the value contain numbers? I put an input with value of 11.5, 12, 12.5 and did not return the value in the array.

  • 1

    You are sure, because I tested with these values and it worked. Ta doing so: value="11.5" ?

  • 1

    Yes, I tested with these values only in the string, then I went to test with Curl, but it does not return.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.