Brad
Brad

Reputation: 39

How to extract strings from a file in PHP

I have a txt file.

source.txt:

test.com,Test
www.cnn.com,CNN
twitter.com,Twitter

I want to print it like

Output:

<a target="_blank" href="http://test.com">Test</a>
<a target="_blank" href="http://www.cnn.com">CNN</a>
<a target="_blank" href="http://twitter.com">Twitter</a>

My code doesn't work:

$array = explode("\n", file_get_contents('/home/source.txt'));
echo '<a target="_blank" href="http://' . $array[0] . '">'. $array[1] . '</a>'

Upvotes: 0

Views: 1328

Answers (1)

Boris Savic
Boris Savic

Reputation: 781

// explode file by end off line
$array = explode("\n", file_get_contents('/home/source.txt'));

// here $array[0] should be "test.com,Test"

// lets loop
foreach($array as $item) {

    // now create array from our line of text
    $data = explode(",", $item);

    // output
    echo '<a target="_blank" href="http://' . $data[0] . '">'. $data[1] . '</a>';
}

Better?

Upvotes: 5

Related Questions