简体   繁体   English

PHP DOM返回为html

[英]PHP DOM return as html

I have an xml file slider.xml with html code inside: 我有一个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>

In PHP I would like to: 1. load it (using simplexml, dom or other better solution) and store in a variable $xml; 在PHP中,我要:1.加载它(使用simplexml,dom或其他更好的解决方案)并存储在变量$ xml中; 2. create an array $head with both $xml->head->children(); 2.使用$ xml-> head-> children()创建一个数组$ head; 3. return the original html code for $head[0] and $head[1]. 3.返回$ head [0]和$ head [1]的原始html代码。

I have tried using this code: 我尝试使用此代码:

$xml = simplexml_load_file('slider.xml');
$head = $xml->head->children();
foreach($head as $element){
    echo $element->asXML();
}

but it returns self-closing tags: 但它返回自动关闭标签:

<script async="async" src="ws-custom/plugins/slider.js"/>
<script async="defer" src="ws-custom/plugins/functions.js"/>

which is not valid html code for W3C http://validator.w3.org/nu/ 这不是W3C的有效html代码http://validator.w3.org/nu/

I would like also to be able to write only async, ie because it's valid html, but with simplexml it's not valid xml. 我也希望能够只编写异步,即因为它是有效的html,但使用simplexml时它不是有效的xml。

Thank you very much. 非常感谢你。 Best regards. 最好的祝福。

I've edited the script, now it works perfectly. 我已经编辑了脚本,现在可以正常使用了。 Note please the row 6: $element[] = null; 请注意第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 can't output the empty tags properly, you should use DOMDocument instead (LIBXML_NOEMPTYTAG doesn't work in SimpleXML)... 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;
}

This code gets a start point (the <head> tag), as you only want the first one it uses [0] and finds the <script> tags inside the start point. 该代码获得一个起点( <head>标记),因为您只希望它使用的第一个标记[0]并在起点内找到<script>标记。

Which with the test source gives... 哪个与测试源一起给出...

<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM