City/State Lookup from USPS?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
erika
Forum Newbie
Posts: 17
Joined: Sat Oct 25, 2008 5:27 pm

City/State Lookup from USPS?

Post by erika »

I have a multi-page form and am using sessions to record data from page to page. On the first page the user enters a zip code. On another page I want to automatically fill in the city and state (this form applies to US-based users only) based on the entered zip code. I've researched this and can't find a script that does quite what I want or instructions for how to create one.

I've never done *anything* like this before. I have a vague understanding that I need to use some kind of API to access usps.com and have registered with them. Apparently I'm supposed to send them a string via get or post and they send me back some XML containing the desired information.

Sounds great! But I have a "minor" problem... I'm an HTML coder pretending to be a real programmer and I have no idea what I'm talking about. :oops: I've learned a lot through these forums and hope someone will be kind enough to hold my hand through this. I understand basic PHP, including interfacing with MySQL, right up until I get to "classes" then I get a little fuzzy, so I'm hoping to do this without classes... unless someone has a really good explanation for them that I might understand.

The code sample the USPS provides is all full of JavaScript, which I'd like to avoid, and various other things that don't work well outside of IE. I'd like to do this all server-side.

I guess my first question is: Can I send the request to the USPS server without specifically using the submit button to do that? If so, how?

And my second question is: Then what? How do I a) get the information back from them and b) do something with it?

Thank you for any assistance and tips.
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: City/State Lookup from USPS?

Post by Darhazer »

You can send the request server-side and the easier way is using cURL. I believe you can find many examples of this in the forum.
By the way, if server allows opening URL by file function, you can retrieve the XML just like this:

Code: Select all

$response = file_get_contents($url);
But this depends on server settings
Post Reply