It would be very interesting to know how is organized the txt file with the postal information.
Here in Brazil there is a free Web Service available on Virtual Republic that may be useful. There are several explanations and examples of how to use in several languages.
There is also 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 type files (Comma Separated Values). It has a very good publication on this blog on how to use this type of file in PHP; passing to an Array you can browse it for information.
Regardless of how you can extract data from the data table, you will need Javascript to build an AJAX function that automatically inserts the data. 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 so that when the user leaves the zip code the data is searched and filled in automatically. For ease, we may 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 makes the work much easier is that the data is being passed on in JSON format. An array of data 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 gets a little slow and consumes many 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 an external API/Web Service, still write a PHP script to take this data and pass it to Javascript.
I hope it helped.
Want to do this on the server or client side? You can put an excerpt of the type of data that the zip file has?
– Sergio
How big is this file . txt? Depending on the size, if it is above 1MB, the best strategy is to leave the data on the server.
– renedet
the size is 5,55KB . I can put the php code and fetch the information from the txt file?
– ChrisAdler
Only at the information level,
concelho
that’s how they talkmunicípio
in Portugal. I researched to know this because it was sounding strange.– Math