xd3*_*d3v 3 javascript php dom
把头发拉出来......
我需要使用PHP在两个不同的点处将一堆html插入到另一组html中.
$ a从另一个类的函数返回给我.我需要在$ a中插入$ b,使$ b元素成为$ a元素的父元素.
<?php
$a = '
<div id="one">
<div id="two">
<div id="three">Hi</div>
</div>
</div>
';
$b = '
<div id="red">
<div id="blue"></div>
</div>
<div id="green">
<div id="yellow">there</div>
</div>
';
?>
Run Code Online (Sandbox Code Playgroud)
需要最终:
<?php
$c = '
<div id="one">
<div id="two">
<div id="red">
<div id="blue">
<div id="three">Hi</div>
</div>
</div>
<div id="green">
<div id="yellow">there</div>
</div>
</div>
</div>
';
?>
Run Code Online (Sandbox Code Playgroud)
注意如何将$ b插入$ a,使所有$ ba child变为"two".但与此同时,"三"成为"蓝色"的孩子."绿色"和"黄色"保持原有关系,但现在嵌套在"两个"之下.
现实世界的例子......
<?php
$a = '
<div class="ginput_complex ginput_container">
<span class="ginput_full">
<input name="input_5" id="input_4_5" type="file" value="" class="medium" tabindex="5">
<label for="input_4_5" class="ginput_post_image_file">File</label>
</span>
<span class="ginput_full ginput_post_image_title">
<input type="text" name="input_5.1" id="input_4_5_1" value="" tabindex="6">
<label for="input_4_5_1">Title</label>
</span>
<span class="ginput_full ginput_post_image_caption">
<input type="text" name="input_5.4" id="input_4_5_4" value="" tabindex="7">
<label for="input_4_5_4">Caption</label>
</span>
<span class="ginput_full ginput_post_image_description">
<input type="text" name="input_5.7" id="input_4_5_7" value="" tabindex="8">
<label for="input_4_5_7">Description</label>
</span>
</div>
';
$b =
'
<div class="container">
<div class="row fileupload-buttonbar">
<div class="span7">
<span class="btn btn-success fileinput-button">
<i class="icon-plus icon-white"></i>
{{{{{{{{ THIS IS WHERE I MY FILE INPUT SHOULD GO }}}}}}}}}}}
</span>
<button type="submit" class="btn btn-primary start">
<i class="icon-upload icon-white"></i>
<span>Start upload</span>
</button>
<button type="reset" class="btn btn-warning cancel">
<i class="icon-ban-circle icon-white"></i>
<span>Cancel upload</span>
</button>
<button type="button" class="btn btn-danger delete">
<i class="icon-trash icon-white"></i>
<span>Delete</span>
</button>
</div>
</div>
</div>
';
$doc = new DOMDocument;
$doc->loadHTML($a);
$x = new DOMXPath($doc);
?>
Run Code Online (Sandbox Code Playgroud)
我正在使用$ x-> query('//*[@ id ="input_4_5"]')来到我想要开始工作的节点.从那里开始,我一直在使用新的DOMElement和importNode以及appendChild,replaceChild和insertBefore的变体来尝试遍历DOM树.但坦率地说,即使我成功遍历它,我也无法弄清楚如何插入/追加我正在使用的大块代码.
我正在使用SimpleHTMLDom解析器
试试这个:
<?php
require_once( 'simple_html_dom.php' );
$a = '
<div id="one">
<div id="two">
<div id="three">Hi</div>
</div>
</div>
';
$b = '
<div id="red">
<div id="blue"></div>
</div>
<div id="green">
<div id="yellow">there</div>
</div>
';
$a = str_get_html( $a );
$c = str_get_html( $b );
$c->find( 'div[id=blue]', 0 )->innertext = $a->find( 'div[id=two]', 0 )->innertext;
$a->find( 'div[id=two]', 0 )->innertext = $c->save();
echo $a;
?>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.