dongtan6695 2016-07-13 14:43
浏览 37
已采纳

使用PHP将div插入HTML文件

Using PHP, I'm trying to add a div in parsed HTML, with the insertion location depending on an existing tag's ID.

I get a generated HTML file (which I have no control of) that is basically read-only. My job is to get that HTML file, add a few divs (buttons and other stuff), and resend it back.

This is where it gets a little bit tricky: where I need to add the divs (the ones I'm adding with buttons and stuff) depends on a div ID that can appear multiple times in the HTML file.

In order for my added div to work properly, it must be added before the parent div of the tagged, identifiable div.

Simply put:

... some html

<--- where i want to put our lovely div

<div> // no  tags no info just a simple div

    <div id="myId">
        ... some html
    </div>

</div>

... some html
  • 写回答

1条回答 默认 最新

  • doufen3838 2016-07-15 19:06
    关注

    Your absolute best option, imo would be to use PHP's native DOMDocument: http://php.net/manual/en/class.domdocument.php

    There's quite a learning curve to this so I worked up something that should get you going in the right direction - if not provide a solution altogether. I've included line by line comments here to explain each step:

    // the filename you want to parse
    $filename = './test.html';
    
    // an array of replacement html snippets and the id of the child element.
    // html will be inserted before parent of each child with a matching ID as you described
    $replacements = [
        [
            'id'     => 'myId',
            'insert' => '<button>Insert before parent of #myId</button>'
        ],
        [
            'id'     => 'myId2',
            'insert' => '<button>Insert before parent of#myId2</button>'
        ]
    ];
    
    // instantiate DOMDocument and read the html file
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTMLFile('./test.html');
    
    // get an array of all dom elements
    $elements = $dom->getElementsByTagName('*');
    
    // iterate through dom elements
    foreach($elements as $element) {
    
        // check if this element has an 'id' attribute
        if ($element->hasAttribute('id')) {
    
            // iterate through replacement array
            foreach ($replacements as $i => $replacement) {
    
                // if element's id is a match then add this node to our array
                if ($element->getAttribute('id') == $replacement['id']) {
                    $replacements[$i]['nodes'][] = $element;
                }
            }
        }
    }
    
    // iterate through replacements again
    foreach ($replacements as $replacement) {
    
        // iterate through nodes we found which matched
        foreach ($replacement['nodes'] as $node) {
    
            // create a DOMDocument node from an html string
            $html = $dom->createDocumentFragment();
            $html->appendXML($replacement['insert']);
    
            // insert this node before parent
            $node->parentNode->parentNode->insertBefore($html,$node->parentNode);
        }
    }
    
    // output the revised html
    echo $dom->saveHTML();
    
    // note - if your html doesn't have <html> and <body> tags they will be automatically added by DOMDOcument
    // you can work around this and get only body innerhtml with something like this
    echo str_replace(['<body>','</body>'],'',$dom->saveHTML($dom->getElementsByTagName('body')->item(0)));
    

    I created a test document with the following html called test.html. I intentionally used myId twice to demonstrate that this will in fact match every element regardless of validity:

    <div> // no  tags no info just a simple div
        <div id="myId">
            ... some html
        </div>
    </div>
    
    <div> // no  tags no info just a simple div
        <div id="myId2">
            ... some html
        </div>
    </div>
    
    <div> // no  tags no info just a simple div
        <div id="myId">
            ... some html
        </div>
    </div>
    

    The php code above outputs the following:

    <button>Insert before parent of #myId</button><div> // no  tags no info just a simple div
        <div id="myId">
            ... some html
        </div>
    </div>
    
    <button>Insert before parent of #myId2</button><div> // no  tags no info just a simple div
        <div id="myId2">
            ... some html
        </div>
    </div>
    
    <button>Insert before parent of #myId</button><div> // no  tags no info just a simple div
        <div id="myId">
            ... some html
        </div>
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值