2016-07-13 2 views
2

PHP를 사용하여 삽입 된 위치를 기존 태그의 ID에 따라 파싱 된 HTML에 div를 추가하려고합니다.PHP를 사용하여 HTML 파일에 div를 삽입

기본적으로 읽기 전용 인 생성 된 HTML 파일 (제어 할 수 없음)이 표시됩니다. 내 직업은 그 HTML 파일을 가져 와서 몇 개의 div (버튼과 다른 것들)를 추가하고 그것을 다시 다시 보내는 것이다.

여기가 조금 까다 롭습니다. div 파일 (버튼과 물건으로 추가하는 부분)을 추가해야하는 곳은 HTML 파일에 여러 번 나타날 수있는 div ID에 따라 다릅니다.

추가 된 div가 제대로 작동하려면 태그가 지정된 식별 가능한 div의 상위 div 앞에 추가되어야합니다.

는 간단히 말해 :

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

예 좋을 텐데 ... – Jah

+0

음 :

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

PHP 코드는 위의 다음과 같은 출력 : 나는 의도적으로 모든 요소에 관계없이 유효 실제로 경기에서이 뜻이 있음을 입증하기 위해 두 번 myId을 사용 html 파일에서 태그를 검색하는 방법을 찾으려고 할 때 부모 태그를 가져 와서 코드 문자열 앞에 삽입하십시오. 부모 태그를 가져 오는 것이 나를 괴롭게하는 것입니다 – Z3R0

+0

if/else 문을 구성하지 않으시겠습니까? ($ divID === 'abc') {insert ...} else {do ​​something} 대신에 – Kray

답변

3

귀하의 절대 가장 좋은 방법은, IMO에서 PHP의 기본있는 DOMDocument를 사용하는 것입니다 : http://php.net/manual/en/class.domdocument.php이 꽤 학습 곡선이있다

그래서 당신이 가야 할 게를했습니다 올바른 방향으로 - 해결책을 제시하지 못한다면

// 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))); 

내가 test.html를라는 다음과 같은 HTML과 테스트 문서를 만든 : 나는 라인으로 라인이 각 단계를 설명하기 위해 여기에 코멘트 포함 시켰습니다.

<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> 
+0

Thx 많이 완벽하게 작동합니다. – Z3R0

관련 문제