Function Result in an Array of Objects?

0

How to transform the output of this function into a array ? In future I would like to call only the result of a particular row, 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");
?>
    
asked by anonymous 06.03.2018 / 01:11

1 answer

1

It would create an array to add the words to the array and then just get 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?

    
06.03.2018 / 02:08