php学习??xml

WBOY
WBOY원래의
2016-06-23 14:34:09765검색

【创建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);


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.