Function Result in an Object Array?

Asked

Viewed 34 times

0

How to turn the output of this function into a array? In the future I would like to call only the result of a specific line, such as $palavraschave[1].

<?php
$url= 'https://www.telelistas.net/ac/acrelandia';

function palavras_chave($pc){
    $doc= new DOMDocument();
    $doc->loadHTML(file_get_contents($pc));
    $finder = new DomXPath($doc);
    $tableid="Content_dataListPalavrasChave";
    $nodes = $finder->query("//*[contains(concat(' ', normalize-space(@id), ' '), ' $tableid ')]");
    foreach ($nodes as $node){
        $links= $node->getElementsByTagName("a");
        foreach ($links as $link){
            //echo $link->getAttribute("href")."<br>";
            $linktratado = $link->getAttribute("href")."<br>";
            parse_url($linktratado, PHP_URL_PATH);
            $keys = explode("/", $linktratado);
            echo $keys[5];
        }
    }
}

palavras_chave("$url");
?>

1 answer

0


It would create an array to add the words to the array and then just take the desired position:

<?php
$url= 'https://www.telelistas.net/ac/acrelandia';

function palavras_chave($pc){
    $array = array(); //Cria uma variável array
    $doc= new DOMDocument();
    $doc->loadHTML(file_get_contents($pc));
    $finder = new DomXPath($doc);
    $tableid="Content_dataListPalavrasChave";
    $nodes = $finder->query("//*[contains(concat(' ', normalize-space(@id), ' '), ' $tableid ')]");
    foreach ($nodes as $node){
        $links= $node->getElementsByTagName("a");
        foreach ($links as $link){
            //echo $link->getAttribute("href")."<br>";
            $linktratado = $link->getAttribute("href")."<br>";
            parse_url($linktratado, PHP_URL_PATH);
            $keys = explode("/", $linktratado);
            array_push($array, $keys[5]); //Adiciona a string ao array
        }
    }

    return $array; //Retorna o array
}

$teste = palavras_chave("$url"); //Atribui o array a variável teste

echo $teste[0]; //Mostra a posição 0 do array
?>

That?

  • Awesome! That’s right, thank you very much.

Browser other questions tagged

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