sexta-feira, 27 de março de 2015

PHP Web Service

In this post we will be developing a web service with PHP. The data is in a MySQL database and the output format is optional between XML and JSON.

In order to collect the data we will be using MySQLi.

The service won't be requiring any credentials and there won't be any limits to the number of requests although in some cases it would be necessary to consider that possiblities.

First we must define the values needed to connect with the MySQL server.

<?php
$server="server";
$user="userid";
$password="userpassword";
$database="database";
?>

Next is the code that implements de service per say.

<?php

require "config.php";
//connect to the database server
$ligacao=new mysqli($server,$user,$password,$database);
//check connection
if($ligacao->connect_error)
die("Error connecting: ".$ligacao->connect_error);

//options
if(isset($_GET['format']))
$output=$_GET['format'];
else
$output="xml"; //by default
if($output!='JSON'&&$output!='json'&&$output!='xml'&&$output!='XML')
$output="xml";

//data
$sql="SELECT * FROM test_users";
$resultado=$ligacao->query($sql);
if($resultado->num_rows>0){
while($registo=$resultado->fetch_assoc())
$registos[]=array("record"=>$registo);

header("Cache-Control: no-cache, must-revalidate");
if($output=="xml"||$output=="XML"){
$conteudo="Content-type: text/xml; charset=utf-8";
header($conteudo);
$linhas="";
$linha="";
foreach($registos as $index => $registo)
{
if(is_array($registo)){
foreach($registo as $campo => $valor){
if(is_array($valor)){
foreach($valor as $tag => $val)
$linha.=adicionarTag($tag,htmlentities($val));
}
$linha=adicionarTag("record",$linha);
}
}
$linhas = $linhas.$linha;
$linha="";
}
echo adicionarTag("records",$linhas);
}else{
$conteudo="Content-type: application/json; charset=utf-8";
header($conteudo);
echo json_encode(array('records'=>$registos));
}
}
function adicionarTag($tag,$texto){
$temp="<".$tag.">".$texto."</".$tag.">";
return $temp;
}
?>

The project can be downloaded here.

Sem comentários:

Enviar um comentário