How to Parse XML data to a PHP variable

孤街浪徒 提交于 2019-12-07 13:24:16

问题


I am mediocre with php and ignorant with XML...if you can be detailed it will help me learn.

I am attempting to use PHP programming to execute a scripts to this link... http://ws.geonames.org/postalCodeSearch?postalcode=VARIABLE_ZIP&country=US. The VARIABLE_ZIP is the actual zip code entered into the form that will submit the information in the link above. The output of that link creates an XML page that i do not want displayed anywhere on my website.

What I want to do is capture the XML data Latitude and Longitude values as variables within php and store them into a database.

1) I have a form

2) The user inputs their zip code into the form

3) upon submitting the form: I want code to capture the XML data generated by the link with the zip code variable added: http://ws.geonames.org/postalCodeSearch?postalcode=90210&country=US (I don't want this page to display anywhere, I just want to capture the data)

4) I want to take those variables back to PHP so I can store them in my database

*Step 3 is an unknown process for me. This is what the XML code generates on a separate page...(i don't want a page to display):

= = = = =

<geonames>
<totalResultsCount>1</totalResultsCount>
<code><postalcode>90210</postalcode>
<name>Beverly Hills</name>
<countryCode>US</countryCode>
<lat>34.09011</lat>
<lng>-118.40648</lng>
<adminCode1>CA</adminCode1>
<adminName1>California</adminName1>
<adminCode2>037</adminCode2>
<adminName2>Los Angeles</adminName2>
<adminCode3/><adminName3/>
</code>
</geonames>

= = = = =

Someone provided me with the following but I am not sure how to execute it and parse the variables I need:

<?php
$pc = $_POST['postalcode'];
$c = $_POST['country'];
$xml = file_get_contents("http://ws.geonames.org/postalCodeSearch?postalcode={$pc}&country={$c}");
file_put_contents("geopost_{$pc}_{$c}.xml",$xml);
?>

Thank you for your assistance!


回答1:


The best thing to do is to see how the XML is structured by navigating directly to the link (I used my own zipcode and country), and then navigate through the tree grabbing the data you need using SimpleXMLElement. This example grabs the Latitude and Longitude:

<?php
$pc = $_POST['postalcode'];
$c = $_POST['country'];
$xml = new SimpleXMLElement(file_get_contents("http://ws.geonames.org/postalCodeSearch?postalcode=".$pc."&country=".$c));
$lat = $xml->code->lat;
$lng = $xml->code->lng;
echo "Lat: $lat<br/>Lng: $lng";
?>

This should help get you started with storing those values.




回答2:


Step 3 is to process the xml with PHP which is outlined quite nicely with these Simple XML examples




回答3:


Take a look at PHPs SimpleXML for how to parse and read the XML data received.



来源:https://stackoverflow.com/questions/10586046/how-to-parse-xml-data-to-a-php-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!