Php利用java解析xml

請先安裝JAVA的執行環境與PHP結合,具體參考https://www.phpx.com/happy/thr78795.html 
或者下載https://www.javax.org/download/php_java.rar 
裡面我寫有個readme.txt說明文檔,這個壓縮包是個簡單的例子。 
要下載我的JAVA源碼請到https://www.javax.org/download/JavaXml.rar 
有其他問題請到https://www.javax.org/提問。 

一開始我想用PHP解析XML,但發現PHP要解析XML有點麻煩,好象PHP5比較方便瞭,但我這邊沒有裝5,還是4.3。後來我看到IBM一篇文章(https://www-900.cn.ibm.com/developer…kit/index.shtml)講到可以利用JAVA來做,所以我現在就試驗瞭一下。 
要解析的XML文件:first.xml,內容如下: 
<?xml version=”1.0″ encoding=”UTF-8″?> 
<product> 
<hello> 
<name>小曾</name> 
<age>20</age> 
</hello> 
<hello> 
<name>雨傘</name> 
<age>20</age> 
</hello> 
</product> 
其中<product>是根,<hello>是節點,一共有兩個,name值名字不一樣,一個是小曾一個是雨傘,年齡一樣。 
下面看PHP解析時候的文件: 
<?php 
$JavaXml = new Java(“JavaXml”); //這裡是生成一個我寫的JAVA解析XML數據的類 
$JavaXml->init(); //這裡為初始化,比如取global.properties文件裡的XML文件目錄(當然你下載瞭例子以後要改成你的XML文件目錄) 
$JavaXml->Parse(“first.xml”); //指定要解析的文件,相對於global.properties文件裡指定的目錄下 
$JavaXml->get(0); //這裡為取得第一個節點 
echo $JavaXml->getValue(“name”).”<br>”; //取得第一個節點name標簽值 
echo $JavaXml->getValue(“age”).”<br>”; //取得第一個節點age標簽值 
$JavaXml->setValue(“name”,”大頭爸爸”); //設置第一個節點name標簽值為大頭爸爸 
$JavaXml->get(1); //這裡為取得第二個節點 
echo $JavaXml->getValue(“name”).”<br>”; //取得第二個節點name標簽值 
echo $JavaXml->getValue(“age”).”<br>”; //取得第二個節點age標簽值 
?> 

$JavaXml->get(0);取得節點位置,比如我的XML文件有兩組<hello>,這裡get(0)的話就是取第一組的<hello> ,get(1)就是取第二組的<hello>. 
最後輸出是 
小曾 
20 
雨傘 
20 
因為$JavaXml->setValue(“name”,”大頭爸爸”); 這句修改瞭第一個節點的name標簽的值,XML文件已經被更新過瞭,所以當再執行一次這個PHP文件的時候結果會成為 
大頭爸爸 
20 
雨傘 
20 

以上簡單幾句就解析完瞭,下面是我的JAVA類,裡面用到瞭JDOM來解析XML。 
import org.jdom.* ; 
import org.jdom.output.* ; 
import org.jdom.input.* ; 
import java.io.* ; 
import java.util.*; 
public class JavaXml { 
public String path=null; 
public String XmlFileName=null; 
public SAXBuilder sax=null; 
public Document doc=null; 
public Element root=null; 
public List xlist=null; 
public Element e=null; 
public Element value=null; 
public String getTest(){ 
return new String(“haha”); 

public JavaXml(){ 

public String init(){ 
InputStream is = getClass().getResourceAsStream(“global.properties”); 
Properties dbProps = new Properties(); 
try { 
dbProps.load( is ) ; 

catch ( Exception e ) { 
return (“error file”); 

this.path=dbProps.getProperty(“XmlPath”); 
return (“ok”); 

public void get(int child){ 
this.e=(Element)xlist.get(child); 

public String getValue(String name){ 
this.value=e.getChild(name); 
return this.value.getText(); 

public void setValue(String name,String value)throws Exception{ 
this.value=e.getChild(name); 
this.value.setText(value); 
XMLOutputter xmlout=new XMLOutputter(); 
xmlout.output(doc,new FileOutputStream(path+XmlFileName)); 

public void Parse(String XmlFileName) 
throws Exception 

this.XmlFileName=XmlFileName; 
this.sax=new SAXBuilder(); 
this.doc=sax.build(new FileInputStream(path+XmlFileName)); 
this.root=doc.getRootElement(); 
this.xlist=root.getChildren(); 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *