Jan de Sterke
Jan de Sterke

Reputation: 21

Import text from txt file into an URL

I was wondering if it is possible to have a text file (for example text.txt) with in that file only 1 word (for example: blue) so I can import this text into an URL on my HTML page.

<a src="localhost/img/TEXTFROMFILE.png"></a>

This way I can change the image by simply typing a word in the text file. I guess you need to import the file and then create a string? But I am not an expert so..

Upvotes: 0

Views: 1557

Answers (2)

Neo Morina
Neo Morina

Reputation: 401

If you want to do that in Php, it would be easy. I'm just showing you an example.

Let just say that the txt file is named blue.txt, than the code will be.

 <?php

    $name = file_get_contents("./blue.txt");
    echo "<a href=\"localhost/img/".$name.".png\"></a>";

?>

Here is the code for achieving it in client side.

Html + plain Javascript

<html>
<head>
</head>
<body>
<script type="text/javascript">
var client = new XMLHttpRequest();
client.open('GET', '/text.txt');
client.onreadystatechange = function() {
  var text = client.responseText;
  var anchor = document.createElement("a");        // Create a <a> element
  annchor.setAttribute("href", "localhost/img/"+text+".png");  
}
client.send();
</script>
</body>
</html>

Upvotes: 1

Luckyfella
Luckyfella

Reputation: 662

Note that "a"-tags have no "src" attribute.

Valid "a" attributes are listed here: https://www.w3schools.com/tags/tag_a.asp

Maybe you meant href instead of src ?

Upvotes: 1

Related Questions