php中DOMElement操作xml文檔執行個體示範_PHP教程

來源:互聯網
上載者:User
複製代碼 代碼如下:
//Store your html into $html variable.
$html="

Rakesh Verma


Example
Google
Yahoo

";
$dom = new DOMDocument();
$dom->loadHTML($html);
//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
//remove and set target attribute
$href->removeAttribute('target');
$href->setAttribute("target", "_blank");
$newURL=$url.".au";
//remove and set href attribute
$href->removeAttribute('href');
$href->setAttribute("href", $newURL);
}
// save html
$html=$dom->saveHTML();
echo $html;
?>

例2
複製代碼 代碼如下:
/*




<班級>
<學生 number="101">
<名字>孫悟空
<名字>孫行者
<年齡>123
<介紹>&*$%特殊字串^&#$&

<學生 number="10"2">
<名字>白骨精
<年齡>140
<介紹>介紹內容


*/
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');
$itemsNodeList = $xmldoc->getElementsbyTagName('學生');
$itemElement = $itemsNodeList->item(0);//得到第一個完整的學生資訊節點
$itemChildsNodeList = $itemElement->getElementsbyTagName('名字');//得到子節點“名字”,也許有多個名字
$itemChildNode = $itemChildsNodeList->item(0);//得到第一個名位元組點
echo $itemChildNode->nodeValue;//輸出節點值
//封裝成函數
$nodeArr = array('名字', '年齡', '介紹');
function getNodeVal($xmldoc, $itemsName, $nodeArr){
$items = $xmldoc->getElementsByTagName($itemsName);
for($i=0; $i < $items->length; $i++){
$item = $items->item($i);
foreach($nodeArr as $node){
$data[$i][] = $item->getElementsByTagName($node)->item(0)->nodeValue;
}
}
return $data;
}
$data = getNodeVal($xmldoc, '學生', $nodeArr);
print_r($data);

http://www.bkjia.com/PHPjc/326712.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/326712.htmlTechArticle複製代碼 代碼如下: ?php //Store your html into $html variable. $html="html head titleRakesh Verma/title /head body a href='http://example.com'Example/a a href='http://googl...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.