It would be very interesting to know how the txt file is organized with the postal information.
Here in Brazil there is a free Web Service available on the Virtual Republic that may be useful. There are several explanations and examples of how to use it in several languages.
There is also the GeoNames, International, and several other Web Services available with a list of several countries. It would be interesting to search more later.
If you still need to use the txt file, try the following. Most of the time they are CSV (Comma Separated Values) files. There is a very good blog post on how to use this type of file in PHP; passing to an Array you can go through it for information.
Regardless of how you can extract the data from the data table, you will need JavaScript to build an AJAX function that will insert the data automatically. How to do this?
First create the fields in your HTML and give a different and specific ID to each of them. Ex.:
<input type="text" id="codigo-postal" /><br />
<input type="text" id="concelho" />
Then create an event for when the user exits the code-post field the data will be searched and populated automatically. To make it easier, we can use the jQuery JavaScript library.
$("#codigo-postal").focusout(function() {
$.getJSON( "busca_codigo.php", {
codigo: $("#codigo-postal")[0].value
} )
.done(function( data ) {
if(data.encontrou == 1) {
$("#concelho")[0].value = data.conselho
} else {
alert("Código não encontrado!");
}
});
});
An important detail that greatly facilitates the work is that the data is being passed in JSON format. An Array of data in this way can be easily obtained through PHP and easily handled through JavaScript.
It may be that, depending on the database, the iterative search in the txt file is a bit slow and consumes a lot of server resources. Try to use a trusted Web Service that already exists or migrate the data to an SQL Database, for example; something that offers a more optimized search.
The API address that is placed at the beginning of the jQuery.getJSON function must be under the same domain as the HTML page. For security reasons, modern web browsers block access to external addresses through these functions. Therefore, if you are going to use some external API / Web Service, still write a PHP script to take that data and pass it to JavaScript.
I hope you have helped.