Solving a PHP problem using XML in ONE FILE ONLY! Write a PHP script that accept
ID: 3794902 • Letter: S
Question
Solving a PHP problem using XML in ONE FILE ONLY!
Write a PHP script that accepts HTTP GET and POST requests. When sent a GET request, your script should generate HTML markup containing a simple form with a text input box like that shown below. Enter XML: The user is allowed to enter simple XML into the text box to perform an arithmetic operation, by specifying the type of operation: add/subtract/multiply/divide, and a pair of numbers on which to perform the operation. When the user clicks the Submit button shown above, the PHP script should be sent a POST request with the XML entered by the user. Your script will need to parse the XML to perform the requested arithmetic operation. Ensure that your script can parse and understand the XML code below and perform the requested 'add' operation. add 5 3 The parser should also be able to handle the other arithmetic operations including subtract, multiply and divide. It should also report parse errors and invalid arithmetic operations, and handle divide-by-zero errors.Explanation / Answer
HTML - PHP code for the question Above.
<html>
<body>
<form action = "" method = "post">
Enter XML :-
<textarea name = "myxml" width = "500px" height = "400px"></textarea>
<br/>
<input type = "submit">
</form>
<?php
if($_SERVER["REQUEST_METHOD"]=="POST"){
$myXmlData = $_POST["myxml"];
$xml = simplexml_load_string($myXmlData)
$oper = $xml->operation;
$num1 = $xml->number1;
$num2 = $xml->number1;
if($oper == 'add'){
$answer = $num1 + $num2;
}
else if($oper == 'multiply'){
$answer = $num1 * $num2;
}
else if($oper == 'divide'){
$answer = $num1 / $num2;
}
else if($oper == 'subtract'){
$answer = $num1 - $num2 ;
}
else{
$answer = '';
}
echo "The result of the $oper operation on $num1 and $num2 is $answer";
}
?>
By using the above form, When the user enters the xml text in the text area space and hits on submit button, the data is transferred through HTTP POST method. The Php script written above looks in the Global POST variable and parse the xml data into php object. You can easily access the variable names in an object by using the arrow (-->) operator. After getting the data, the resulting operation based on the data entered is done and the data is displayed in the front end by using PHP echo. This is very easy one. Save the above code in .php extension file and Practice again using the above code for learning. Please Note that PHP is a server side programming, so you need to install apache PHP server on your system for running PHP files.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.