How to Parse XML data to a PHP variable - php

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!

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.

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

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

Related

Sending url parameters through file_get_contents returns nothig

I am trying to scrape a website in order to get latitude and longitude for counties in the us(there are 3306 thus why I am trying to do it through code and not manually)
I am using the code below
function GetLatitude($countyName,$stateShortName){
//Create DOM from url
$page = file_get_contents("https://www.mapdevelopers.com/geocode_tool.php?$countyName,$stateShortName");
$doc = new DOMDocument();
$doc->loadHTML($page);
$node = $doc->getElementById("display_lat");
var_dump($doc);
}
GetLatitude("Guilford County","NC");
This returns nothing but if I change the url to get without the parameters like "https://www.mapdevelopers.com/geocode_tool.php" then I can see that $doc now has some information in it but that is not useful because the value I need (latitude) is dependent upon the parameters passed into the url.
How do I solve this issue?
EDIT:
Based on the suggestion to encode the parameters I changed my code to this and now the document contains information but appears as though it is ignoring the parameters
<?
function GetLatitude($countyName,$stateShortName){
$countyName = urlencode($countyName);
$stateShortName = urlencode($stateShortName);
//Create DOM from url
$page = file_get_contents("https://www.mapdevelopers.com/geocode_tool.php?address=$countyName,$stateShortName");
$doc = new DOMDocument();
$doc->loadHTML($page);
$node = $doc->getElementById("display_lat");
var_dump($doc);
}
GetLatitude("Clarke County","AL");
?>
Your issue is that the latitude information etc isn't present on page load, and java script puts it there
You're going to have a hard time trying to run a webpage with JS and scraping it from PHP without something in the middle, maybe re-try this project with something like puppet or phantomjs so you can run your script against a real browser.
Searching the page there is a ajax request to https://www.mapdevelopers.com/data.php
Sending a POST or GET request will give you the response you are looking for

Quill - JSON > PHP > MYSQL - How to parse data from quill to php for processing?

Wizzards :)
I really want to use Quill richtext editor but I have no real knowledge of JSON or how is parses the so called "Deltas".
Basically, I need to collect the page from the editor and process it with php before storing it in the mysql database, and, from the database back to the editor if user wishes to update an existing post. It needs to be able to parse text and multiple images...
I don't have 3 months a piece to learn js/json, can anyone help me out with this one? Thank youuu!
So acording to the Quill documentation (https://quilljs.com/docs/api/) you can use var delta = quill.getContents(); to collect the data. Would it be something like this with an onclick() function? I dont even know with js if it has to be within a form? remember I don't know js :)
<script>
onclick(does this); // or can it be updated as the user creates the document?
var delta = quill.getContents();
// what then?
</script>";
The php would require a different variable if each image to be processed, perhaps in an array?
<?php
$images = array();
$images[0] = 'json/delta/quill image?';
$images[1] = 'etc...';
$images[2] = 'etc...';
$images[2] = 'wtf...';
?>
Why on earth they don't have a simple example of how to do this I don't know, its an all too common problem with these things.

Actionscript to php then to word template and replace variables

I need to write a code which can do following using actionscript:
1. Send the variables to a php
2. php should open a [re designed word document.
3. Specific word document entries should be replaced with the variables sent from actioncript retaining the formatting of the template.
4. Save the document and provide a link for its download OR just mail it to an address.
I have asked few questions before which very pretty simple compared to this and i did not get any answer for it.. I dont know if this will either. If possible please help me.
To send the variables from ActionScript you would need to do something like the following:
var http:HTTPService = new HTTPService();
http.url = "http://www.yourWebsite.com/yourPhpFile.php";
http.method = "POST";
var variablesToSend:Object = new Object();
for (var varName:String in yourVariables){
variablesToSend[varName] = yourVariables[varName];
}
http.send(variablesToSend);
From "yourPhpFile.php" I would suggest adding some special keywords to search for in the template and do a str_replace() with the variables received through the $_POST object. I'm no php expert but something like:
$yourFilePath = "C:\your\file\path\here.txt";
$yourFileAsString = file_get_contents($yourFilePath);
foreach($_POST as $key=>$value){
$yourFileAsString = str_replace($key,$value,$yourFileAsString);
}
file_put_contents(genNewFileName(),$yourFileAsString);

Sending XML file through PHP remote url

The situation is as follows. I have to send a defined XML to an url http:\\www.example.com:1234 with some variables that I have to previously define.
XML is like this:
<Title1>
<Title2>Some Text</Title2>
<Title3>Variable 1</Title3>
<Title4>Some Text</Title4>
<Title5>
<Title51>Variable 2</Title51>
</Title5>
</Title1>
But, I want to define those variables (1, 2) within an html/php form and get method, so the user can introduce both variables and then click on the submit button from the form to send the XML to the previously URL.
Also, XML should have the "Content-Type","application/x-www-form-urlencoded" header.
Is this possible? I've tried to pass these variables directly to the XML and the best that I've come to is to showing the XML and not parsing the php strings.
Also, I've tried some scripts like simplexml from PHP classes, but with no luck so far.
1) To modify existing XML with new values . Try this
sample.xml :
<Title1>
<Title2>Some Text</Title2>
<Title3>Variable 1</Title3>
<Title4>Some Text</Title4>
<Title5>
<Title51>Variable 2</Title51>
</Title5>
</Title1>
PHP :
$xml = simplexml_load_file("sample.xml");
$xml->Title3 = $_GET['t3']; // Updating <Title3></Title3> from GET method
$xml->Title5[0]->Title51 = $_GET['t5']; // Updating <Title51></Title51> from GET method
$xml->asXML('sample.xml'); // saving the xml file
2)To create new XML file (sample.xml) :
PHP:
$xml = new SimpleXMLElement("<Title1></Title1>");
$xml->Title2='Some Text';
$xml->Title3 = $_GET['t3'];
$xml->Title4='Some Text';
$xml->Title5[0]->Title51 = $_GET['t5'];
$xml->asXML('sample.xml'); // saving the xml file
I have showed you both possibilities mentioned in the comment . Use anyone which comforts you :)

How do I serialize DOM into XML using PHP?

I am attempting to send html data in a question form from my php web application to mechanical turk so a user can see the entire html document from an email to work with. I have had difficulty thus far. In the thread linked below, I attempted to parse the html data using html5-lib.php, but I think I'm still missing a step in order to complete this.
Here's the current error I'm receiving:
Catchable fatal error: Object of class DOMNodeList could not be converted to string in urlgoeshere.php on line 35
Here's the current code I'm working with...
$thequestion = 'click here';
$thequestion = HTML5_Parser::parseFragment($thequestion);
var_dump($thequestion);
echo $thequestion;
//htmlspecialchars($thequestion);
$QuestionXML = '<QuestionForm xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd">
<Question>
<QuestionContent>
<Text>'.$thequestion.'</Text> //<--- Line35
</QuestionContent>
<AnswerSpecification>
<FreeTextAnswer/>
</AnswerSpecification>
</Question>
</QuestionForm> ';
I'm not 100% sure if the parser is what I need to do in order to have this sent correctly - All I want to do is send html through this xml type document - I'm surprised it's been this difficult thus far.
This is somewhat of a continuation of another thread -
What PHP code will help me parse html data in an xml form?
Take a look at DOMDocument for working with DOM/xml in PHP. If you want to embed HTML in your XML, use CDATA sections like this:
$QuestionXML = '<QuestionForm xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd">
<Question>
<QuestionContent>
<Text><![CDATA['.$thequestion.']]></Text>
</QuestionContent>
<AnswerSpecification>
<FreeTextAnswer/>
</AnswerSpecification>
</Question>
</QuestionForm> ';
Not sure exactly what you're after. This is how i would create the XML needed to be transferred.
Please let me know if i misunderstood the question
It also seems that you are missing the QuestionIdentifier node which is mandatory according to the .xsd file.
<?
$dom = new DOMDocument('1.0','UTF-8');
$dom->formatOutput = true;
$QuestionForm = $dom->createElement('QuestionForm');
$QuestionForm->setAttribute('xmlns','http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd');
// could loop this part for all the questions of the XML
$thequestion = 'click here';
//Not sure what this is supposed to be, but its required. Check the specs of the app for it.
$questionID = "";
$Question = $dom->createElement('Question');
$QuestionIdentifier = $dom->createElement('QuestionIdentifier',$questionID);
$QuestionContent = $dom->createElement('QuestionContent');
$QuestionContent->appendChild($dom->createElement('Text',$thequestion));
$AnswerSpecification = $dom->createElement('AnswerSpecification');
$AnswerSpecification->appendChild($dom->createElement('FreeTextAnswer'));
$Question->appendChild($QuestionIdentifier);
$Question->appendChild($QuestionContent);
$Question->appendChild($AnswerSpecification);
$QuestionForm->appendChild($Question);
// End loop
$dom->appendChild($QuestionForm);
$xmlString = $dom->saveXML();
print($xmlString);
?>

Categories