Search code examples
phphtmlparsingdomsimple-html-dom

Simple HTML DOM Parser in input field


I'm trying to get all results from the DOM parser, but I'm getting only the last tag in the input field. If I echo $link isn't a problem. Is there a solution to get all text like I'm getting from echo?

<?php
include_once('simple_html_dom.php');

// Create DOM from URL or file
$link = "https://www.sofascore.com/fr/sevilla-real-betis/qgbsIgb";

foreach ($html->find('div.Header__Main-sc-1dyxed1-0.hkVBhG ul li') as $element){
    $links = $element->find('a');
    foreach ($links as $link) {
        echo $link->plaintext.'<br/>';
    }
}
?>

<input type="text" name="name" value="<?php echo $link->plaintext?>"><br>

Here is the github: https://github.com/inbazhlekov/domm

Id want the value in the input field to be: "Football Espagne LaLiga", not only "LaLiga".


Solution

  • The loop will overwrite $element and $link on each iteration of their respective loops. If you want to access all values after the loop, you need to store the values in a variable.

    You could store them in an array:

    $link = "https://www.sofascore.com/fr/sevilla-real-betis/qgbsIgb";
    
    // Initiate the array we'll use to store the values
    $name = [];
    
    foreach ($html->find('div.Header__Main-sc-1dyxed1-0.hkVBhG ul li') as $element){
        $links = $element->find('a');
    
        foreach ($links as $link) {
            // Push the values into our array instead of echoing them
            $name[] = $link->plaintext;
        }
    }
    ?>
    

    When you want to output it, implode the array with a space as delimiter:

    <input type="text" name="name" value="<?= implode(' ', $name)  ?>"><br>