[英]PHP DOM return as html
我有一個xml文件,其中包含html代碼:
<?xml version="1.0" encoding="UTF-8"?>
<content>
<title>Slider</title>
<head>
<script async="async" src='ws-custom/plugins/slider.js'></script>
<script async="defer" src='ws-custom/plugins/functions.js'></script>
</head>
<footer>
<script async="defer" src='ws-custom/plugins/jquery.js'></script>
</footer>
</content>
在PHP中,我要:1.加載它(使用simplexml,dom或其他更好的解決方案)並存儲在變量$ xml中; 2.使用$ xml-> head-> children()創建一個數組$ head; 3.返回$ head [0]和$ head [1]的原始html代碼。
我嘗試使用此代碼:
$xml = simplexml_load_file('slider.xml');
$head = $xml->head->children();
foreach($head as $element){
echo $element->asXML();
}
但它返回自動關閉標簽:
<script async="async" src="ws-custom/plugins/slider.js"/>
<script async="defer" src="ws-custom/plugins/functions.js"/>
這不是W3C的有效html代碼http://validator.w3.org/nu/
我也希望能夠只編寫異步,即因為它是有效的html,但使用simplexml時它不是有效的xml。
非常感謝你。 最好的祝福。
我已經編輯了腳本,現在可以正常使用了。 請注意第6行:$ element [] = null;
<?php
$xml = new DOMDocument();
$xml = simplexml_load_file('slider.xml');
$head = $xml->head->children();
foreach($head as $element){
$element[] = null;
echo $element->asXML().PHP_EOL;
}
SimpleXML
無法正確輸出空標簽,您應該改用DOMDocument
(LIBXML_NOEMPTYTAG在SimpleXML中不起作用)...
$xml = new DOMDocument('1.0');
$xml->load("slider.xml");
$head = $xml->getElementsByTagName("head");
$headScripts= $head[0]->getElementsByTagName("script");
foreach($headScripts as $element){
echo $xml->saveXML($element, LIBXML_NOEMPTYTAG).PHP_EOL;
}
該代碼獲得一個起點( <head>
標記),因為您只希望它使用的第一個標記[0]
並在起點內找到<script>
標記。
哪個與測試源一起給出...
<script async="async" src="ws-custom/plugins/slider.js"></script>
<script async="defer" src="ws-custom/plugins/functions.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.