php学习??xml

WBOY
WBOYOriginal
2016-06-23 14:34:09758browse

【创建xml】

$dom=new DOMDocument("1.0");
$book=$dom->appendChild($dom->createElement('book'));//创建根元素
$title=$book->appendChild($dom->createElement('title'));//在根元素下创建节点
$title->appendChild($dom->createTextNode('php cookbook'));//在节点下创建子节点
$title->setAttribute("cover","soft");//title节点下创建属性

$sklar=$book->appendChild($dom->createElement('author'));
//$sklar->appendChild($dom->createTextNode('sklar'));

$name=$sklar->appendChild($dom->createElement('name'));
$name->appendChild($dom->createTextNode('fsl'));

$trac=$book->appendChild($dom->createElement('author'));
$trac->setAttribute("cover","feng");
$trac->setAttribute("id","123");
$trac->appendChild($dom->createTextNode('trac'));

$dom->formatOutput=true;
echo $dom->saveXML();
$dom->save('test.xml');
$dom->saveHTMLFile('1.html');

1.htm



php cookbook

fsl

trac

【xml文件处理方法-xpath】


$s=simplexml_load_file("12-1.xml");

$ids=$s->xpath("/people/person/@id");//处理属性
foreach ($ids as $id)
{
echo $id."
";
}

$pname=$s->xpath("/people/person/name");//处理节点

foreach ($pname as $name)
{
echo $name."
";
}

$per=$s->xpath("/people/person");
foreach ($per as $person){
list($age)=$person->xpath("age");
list($city)=$person->xpath("address/city");
list($pro)=$person->xpath("address/province");//处理含有子节点的节点

echo $city."_".$pro.":".$age."
";
}

 

$dom=new DOMDocument;
$dom->load("12-1.xml");
$xpath=new DOMXPath($dom);
$did=$xpath->query("/people/person/@id");

foreach ($did as $id)
{
echo $id->nodeValue."
";
}

$dname=$xpath->query("/people/person/age");

foreach ($dname as $name)
{
echo $name->nodeValue."
";
}


$dper=$xpath->query("/people/person");

foreach ($dper as $persion)
{
$fn=$xpath->query('name',$persion);
echo $fn->item(0)->firstChild->nodeValue." : ";

$fn2=$xpath->query('age',$persion);
echo $fn2->item(0)->firstChild->nodeValue."
";

echo $persion->nodeValue."
";
}

12-1.xml





张俊
20


河北
石家庄
人民东路
13#



刘军
21

吉林
长春
解放南路
25#



周泰
26

广东
深圳
深南路
37#



张群
20

广西
南宁
江南大道
67#


7-2.xsl




 


【应用xslt】

必须打开php扩展php_xsl

$xsl=new DOMDocument;
$xsl->load('7-2.xsl');

$xslt=new XSLTProcessor();
$xslt->importStylesheet($xsl);

$xml=new DOMDocument;
$xml->load('12-1.xml');//双参数问题

$results=$xslt->transformToXml($xml);

$results2=$xslt->transformToURI($xml,'results.html');

$results3=$xslt->transformToDoc($xml);


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn