Function loop returns only one value

2

I'm trying to get data from an online page only that the code is having a problem, it can not process all items in POST mode, within foreach .

Even if I put the items in the list, just get the last item posted. I would like to know how I can solve this problem.

Code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>

<body>
<form id="form1" name="form1" method="post" action="pegavideo.php">
  <p>
    <textarea name="urls" id="urls" cols="100" rows="20"></textarea>
  </p>
  <p>
    <input type="submit" name="gerar" id="gerar" value="Gerar urls do Super Animes" />
  </p>
</form>
<?php 

function pegarDados ($valorUrl) {
   $url = $valorUrl;
   $html = file_get_contents($url);
   $doc = new DOMDocument();
   @$doc->loadHTML($html);
   $tags = $doc->getElementsByTagName('source');
   foreach ($tags as $tag) { return $tag->getAttribute('src').'<br/>';}
}


$dados = $_POST['urls'];
$valoresUrl = explode("\n",$dados);
for($i = 0; $i < count($valoresUrl); $i++) {
   echo pegarDados($valoresUrl[$i]);
}
?>
</body>
</html>
    
asked by anonymous 28.07.2018 / 01:23

1 answer

3

Here is a problem:

 function pegarDados ($valorUrl) {
    $url = $valorUrl;
    $html = file_get_contents($url);
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $tags = $doc->getElementsByTagName('source');
    /// este foreach nunca vai sair da primeira iteração:
    foreach ($tags as $tag) { return $tag->getAttribute('src').'<br/>';}
 }

When foreach happens, return will already exit the function returning only the first src . If you want to return a separate list with <br/> you need something like this:

   ...
   $tags = $doc->getElementsByTagName('source');
   $lista = '';
   foreach ($tags as $tag) { $lista .= $tag->getAttribute('src').'<br/>';}
   return $lista;
 }

In this way, the foreach at each iteration will append the desired src to $ list, and after the loop, return the variable $lista fed into the loop.


Remarks:

  • The tag should probably be <br> . Using <br\> only makes sense if you are making a legacy page in XHTML, or have some reason whatever to process the output in XML.

  • When executing a statement only in the loop, you can simplify it without the { } :

    foreach ($tags as $tag) $lista .= $tag->getAttribute('src').'<br>';
    

    Of course, you should stay true to the style you adopted for the rest of the code.

  • Here you double the variable seemingly at random:

    $url = $valorUrl;
    $html = file_get_contents($url);
    

    You could simply do:

    $html = file_get_contents($valorUrl);
    
  • Instead of this error suppression in @$doc->loadHTML($html); , it might be better to treat the error conditionally.

28.07.2018 / 02:21