Create a Basic Web Service Using PHP, MySQL, XML, and JSON

Create a Basic Web Service Using PHP, MySQL, XML, and JSON

Create-a-Basic-Web-Service-Using-PHP-MySQL-XML-and-JSON
Spread the love
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Below is a very basic web service using PHP and MySQL. The output of this web service is either XML or JSON.

In the web service, I’m trying to get a list of all active users from the database.

	//connect to the db
	$conn = mysql_connect("localhost","username","password") or die("Cannot connect to the DB");
	mysql_select_db("db_name",$conn) or die("Cannot select the DB");
	
	//get the variables or set them to default
	$num_users = isset($_GET["num"]) ? intval($_GET["num"]) : 10; //10 is the default
	$format = strtolower($_GET["format"]) == "json" ? "json" : "xml"; //xml is the default

	//get the details from the database
	$query = "SELECT firstname, lastname FROM users WHERE user_isactive = 'y' ORDER BY user_id DESC LIMIT $num_users";
	$result = mysql_query($query, $conn);

	//create an array of the data fetched from the database
	$users = array();
	if(mysql_num_rows($result)) {
		while($user = mysql_fetch_assoc($result)) {
			$users[] = array('user'=>$user);
		}
	}

	//output the requested format
	if($format == "json") {
		header("Content-type: application/json");
		echo json_encode(array('users'=>$users));
	}
	else {
		header("Content-type: text/xml");
		echo "<users>";
		foreach($users as $index => $user) {
			foreach($post as $key => $value) {
				echo "<$key>";
				if(is_array($value)) {
					foreach($value as $tag => $val) {
						echo "<$tag>$val</$tag>";
					}
				}
				echo "</$key>";
			}
		}
		echo "</users>";
	}

Here is a sample URL of how the first 10 rows can be retrieved in XML format.

https://www.shounakgupte.com/web-service.php?num=10&format=xml

The above URL will retrieve the data below:

<users>
	<user>
		<firstname>John</firstname>
		<lastname>Doe</lastname>
	</user>
        <user>
		<firstname>Jane</firstname>
		<lastname>Doe</lastname>
	</user>
</users>
Rating: 1.0/5. From 1 vote.
Please wait...
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Related Post