Home >Backend Development >PHP Tutorial >PHP operates xml, xml is commonly used

PHP operates xml, xml is commonly used

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-29 09:10:46865browse

1. Understand common protocols:
FTP (File Transfer Protocol): Remote file transfer protocol, allowing users to copy files on the remote host to their own computer.
SMTP (Simple Mail transfer Protocol): Simple Mail Transfer Protocol, used to transfer emails.
NFS (Network File Server): Network file server that allows multiple computers to transparently access each other's directories.
HTTP Hypertext Transfer Protocol:
HTTP is an object-oriented protocol belonging to the application layer. Due to its simple and fast way, it is suitable for distributed hypermedia information systems. It was proposed in 1990 and has been continuously improved and expanded after several years of use and development. The sixth version of HTTP/1.0 is currently used in the WWW, and the standardization work of HTTP/1.1 is in progress. The main features of the HTTP protocol can be summarized as follows:
1. Support client/server mode.
2. Simple and fast: When a client requests a service from the server, it only needs to transmit the request method and path. Commonly used request methods are GET, HEAD, and POST. Each method specifies a different type of contact between the client and the server.
Due to the simplicity of the HTTP protocol, the program size of the HTTP server is small and the communication speed is very fast.
3. Flexible: HTTP allows the transmission of any type of data object. The type being transferred is marked by Content-Type.
4. No connection: The meaning of no connection is to limit each connection to only process one request. After the server processes the client's request and receives the client's response, it disconnects. This method saves transmission time.
5. Stateless: The HTTP protocol is a stateless protocol. Stateless means that the protocol has no memory ability for transaction processing. The lack of status means that if subsequent processing requires the previous information, it must be retransmitted, which may result in an increase in the amount of data transferred per connection. On the other hand, the server responds faster when it does not need previous information.
2. Understand xml:
When XML (Extensible Markup Language) was introduced to the software industry in February 1998, it brought a storm to the entire industry. For the first time, the world has a universal and adaptable format for structuring documents and data, not just on the Web, but everywhere.
XML refers to Extensible Markup Language.
HTML refers to Hypertext Markup Language.
php refers to Hypertext Preprocessing Language.
xml provides a communication bridge between different platforms and different languages.
xml is essentially a text file. It is used to describe the structure of data
Basic syntax of xml:
xml has strict grammatical rules
xml must be declared first

xml must create the root element
All elements in xml must appear in pairs
xml is case sensitive
xml element nesting must be correct
xml element attributes must be Use "" to include
XML documents use self-describing and simple syntax. The most basic components of an XML document include: declarations, processing instructions (optional) and elements. The following is a simple



My webpage
lyle_zhang
This is the content@! Amazing 2013! I wish all the students find their ideal jobs!

Explanation:
Document declaration

xml tag indicates that it is an xml document, followed by The two attribute values ​​indicate its version number and encoding standard. Standalone takes yes to indicate that the file does not reference other external XML files.
3. Webservice related to xml.
xml Web Service is the basic building block for distributed computing on the Internet. Open standards and a focus on communication and collaboration between users and applications have created an environment in which XML Web Services become the platform for application integration.
xML Web Services can specify their interfaces in great detail, which enables users to create client applications to communicate with them.
xML Web Service provides useful functionality to web users through standard web protocols. In most cases the SOAP protocol is used.
soap is the communication protocol of XML Web Service.
4. The difference between xml html xhtml dhtml:
The design difference between XML and HTML is:
XML is used to store data, focusing on the data itself.
HTML is used to define data, focusing on the display mode of the data
XHTML (The Extensible HyperText Markup Language (Extensible Markup Language)) is actually an upgraded version of HTML. The purpose of this version is to make it easier for people to accept XML, because XML is the future direction of web development. In essence, XHTML is a transitional technology that combines some of the powerful functions of XML and most of the simple features of HTML.
DHTML: To be precise, DHTML is just a concept for making web pages. In fact, no organization or institution has ever launched a so-called DHTML standard or technical specification. DHTML is not a technology, standard or specification. DHTML is just a design concept that integrates and applies existing web page technologies and language standards to create web pages that can still change the effect of page elements in real time after downloading. DHTML is based on the original technology and can be divided into three aspects:
First, HTML, which is the various page element objects in the page, they are dynamically manipulated content;
Second, CSS, CSS attributes are also dynamically manipulated content, thereby obtaining dynamic formatting effects;
The third is client-side script (such as JavaScript), which actually manipulates the HTML and CSS on the Web page.
Using DHTML technology, web designers can create pages that can interact with users and contain dynamic content. In fact, DHTML allows web designers to dynamically manipulate all elements on a web page - even after the page has been loaded. Using DHTML, web designers can dynamically hide or show content, modify style definitions, activate elements, and position elements. DHTML also enables web designers to display external information on web pages by binding elements to external data sources such as files and databases. All of these functions can be done using the browser without requiring a request to a Web server and without reloading the web page.This is because all functions are included in the HTML file, which is downloaded to the browser at once with the request for the web page.
5. DOM operation xml


aa
bb
cc

dom node reads data
< ;?php
header("content-type: text/html; charset=utf-8");
//dom node reads xml file
$dom = new DomDocument(); //Create DOM object
$dom- >load('1.xml'); //Read XML file
$root = $dom->documentElement; //Get the root of XML data
$nodes=$root->childNodes; //Get XML All child node objects under the root object
echo $nodes->item(1)->nodeValue; //Output name
echo $nodes->item(3)->nodeValue; //Output password
echo $nodes->item(5)->nodeValue; //Output gender
echo $nodes->item(7)->nodeValue; //Output age
//Get attributes
echo $dom-> getElementsByTagName('name')->item(0)->attributes->getNamedItem('abc')->nodeValue;
echo $nodes->item(1)->attributes->getNamedItem ('id')->nodeValue;
readXml($root); //Execute a loop to read the node function and pass the root node object
function readXml($nodes){
if($nodes->hasChildNodes()) {  //判断是否有子节点
           $childNodes=$nodes->childNodes; //获取到所有的字节点列表
            foreach($childNodes as $key=>$node){ //循环子节点列表
                                                                                                                                                         elseif($node->nodeType== XML_TEXT_NODE ){ //Determine whether it is a file node
                        echo $node->nodeValue; // If there is business logic here, write your code here
                                                              using       using ’s ’ using ’s ’ through ’ using ’ using ’s } through through using ’s } }  - } }
to }
}
?>
//dom generates xml document
$doc=new DOMDocument('1.0');
//Create and append node objects in sequence
$root=$doc->appendChild($doc ->createElement('school')); //Create and append the root directory
//Create child nodes
$class1=$root->appendChild($doc->createElement('class1'));
/ /Create child nodes under the class
$stu=$class1->appendChild($doc->createElement('stu'));
//Create attributes and text for stu
$stu->appendChild($doc ->createTextNode('1Class'));
$stu->setAttribute('number','10');
$stu->setAttribute('zhuanye','java');
/**
* The above code generates xml format


1班


*/
//Create child nodes
$class2=$root->appendChild($doc->createElement('class2'));
//Create child nodes under the class
$stu2=$class2 ->appendChild($doc->createElement('stu'));
//Create attributes and text for stu
$stu2->appendChild($doc->createTextNode('1 class'));
$stu2->setAttribute('number','20');
$stu2->setAttribute('zhuanye','php');
//Generate
$doc->formatOutput=true;
$xmlDoc =$doc->saveXML(); //Generate xml and return an xml document
$doc->save('school.xml');
/**
The final result generated by the above code:



1 x73ED;


1班


*/
6. simplexml interface
header( "content-type: text/html; charset=utf-8");
$xml=simplexml_load_file('school.xml');//Return array object
//Loop to read data and attributes
foreach($xml as $key=>$node){
if($key=='class1'){
echo $node->stu;//Directly access the text node of the object //Output result: Class 1
}elseif( $ key == 'class2') {
echo $ node- & gt; stu ['number']; // The access output result of the attribute: 20
}}} // direct access attribute
echo $ xml- & gt; class1; ->stu['zhuanye']; //Output result: java
/**



1班


2班


 */
Get xml remotely and save it
header("content-type: text/html; charset= utf-8");
//Remote access to xml files
$xml=simplexml_load_file('http://127.0.0.1/xml/2.xml');
$xml->asXML('5.xml') ; //Save locally
//Operate your xml document according to your business logic
?>
Seven.
Generate xml document from database data
/**


 
     1
     aa
     bb
     cc
 


**/
$c>mysql_select_db('member' );
mysql_set_charset("utf8");
//Data submission
if(isset($_POST['zhuce'])){
$username=trim($_POST['username']);
$userpwd=trim ($_POST['userpwd']);
$useremail=trim($_POST['useremail']);
//Write to database
$sql="insert into reg(`id`,`name`,`pwd `,`email`) values(null,'$username','$userpwd','$useremail')";
$res= mysql_query($sql);
if($res){
//Query the database
$sql="select * from reg";
$rest=mysql_query($sql);
$users=array();
while($rows=mysql_fetch_assoc($rest)){
$users[]=$rows;
} }
}
  //判断是否有数据
  if( ! empty($users)){
    $xmlString=createXml('users',$users);
    $xmlObj=new SimpleXMLElement($xmlString); //生成xml对象
    $xmlObj->asXML("reg.xml"); //保存
  }
}
//创建xml
 function createXml($boot,$data){
     $xml="<$boot>n";
        foreach($data as $key=>$value){
            if(is_string($key)){
                  $xml.="<$key>";
                    foreach($value as $k=>$val){
                       $xml.="n<$k>".$val."";
                    }
                  $xml.="nn";
            }else{
              $xml.="<$boot.$key>";
                foreach($value as $k=>$val){
                    $xml.="n<$k>".$val."";
                }
               $xml.="nn";
            }
        }
     $xml.="";
      return $xml;
 }
 
?>





注册后将数据写入数据库并将数据生成xml 文档 保存在 api 目录下面


   


       用户名:

       密码:

       邮箱:

       
   
   



远程获取对象:
  
$xml=simplexml_load_file('http://127.0.0.1/xml/reg.xml');
//$memberXml=$xml->asXML('member.xml');
?>



   
   
    注册后将数据写入数据库并将数据生成xml 文档 保存在 api 目录下面




  foreach($xml as $key=>$node){
 ?>
     
         
         
         
         
     
 }
?>
idnamepwdemail
id;?>name;?>pwd;?>email;?>



yahoo Query the Chinese city id address
http://weather.yahoo.com/china/
$xml=simplexml_load_file("http ://xml.weather.yahoo.com/forecastrss?w=2158433&u=c");
echo '
';<br> //var_dump($xml);<br> $arrobj=$xml->channel- >image;<br> //echo $arrobj->url;<br> // print_r($xml->channel);<br> echo '
';

echo '';

echo ''.$arrobj->title.'sian weatherweather forecastxml
header("content-type: text/html;charset=utf-8");
$c//php.weather.sina.com.cn/xml.php? password=DJOYnieT8234jlsK&day=0&city=Chengdu");
file_put_contents('sina_weather.xml',$content);

The above introduces the operation of XML in PHP. XML is commonly used, including Web server, weather forecast, and object-oriented content. I hope it will be helpful to friends who are interested in PHP tutorials.