2017-01-04 22 views
0

我需要幫助使用DOM方法這是代碼PHP需要幫助使用解析HTML元素

<?php 
$html = ' 
    <p>text1</p> 
    <ul> 
     <li>list-a1</li> 
     <li>list-a2</li> 
     <li>list-a3</li> 
    </ul> 
    <p>text2</p> 
    <ul> 
     <li>list-b1</li> 
     <li>list-b2</li> 
     <li>list-b3</li> 
    </ul> 
    <p>text3</p>'; 

$doc = new DOMDocument(); 
$doc->loadHTML($html); 
foreach ($doc->getElementsByTagName('p') as $link) { 
    echo $link->nodeValue."\n", PHP_EOL; 
} 
foreach ($doc->getElementsByTagName('ul') as $link) { 
    $books = $link->getElementsByTagName('li'); 
    foreach ($books as $book) { 
     echo $book->nodeValue, PHP_EOL; 
     // $links3[] = array($ii=> $book->nodeValue,); 
     //$ii++; 
    } 
} 
?> 

創建從HTML文件的元件嵌套數組,這是 程序輸出以創建嵌套數組:

text1 
text2 
text3 
list-a1 
list-a2 
list-a3 
list-b1 
list-b2 
list-b3 

,但我需要得到這個輸出原始的HTML的相同順序

text1 
list-a1 
list-a2 
list-a3 
text2 
list-b1 
list-b2 
list-b3 
text3 

不使用preg或更換方法!!!

+0

顯示確切方式您預期的結果。 not in text –

+0

你的意思是我應該刪除'foreach($ doc-> getElementsByTagName('ul')as $ link)' – filip

+0

謝謝你,但不是soution檢查這個(https://eval.in/708775) – filip

回答

2

要打印值

<?php 

    $html = ' 
     <p>text1</p> 
     <ul> 
      <li>list-a1</li> 
      <li>list-a2</li> 
      <li>list-a3</li> 
     </ul> 
     <p>text2</p> 
     <ul> 
      <li>list-b1</li> 
      <li>list-b2</li> 
      <li>list-b3</li> 
     </ul> 
     <p>text3</p> 
    '; 

    $doc = new DOMDocument(); 
    $doc->loadHTML($html); 

    foreach ($doc->getElementsByTagName('body')->item(0)->childNodes as $node) { 
     if ($node->nodeType === XML_ELEMENT_NODE) { 
      if($node->nodeName == 'p'){ 
        echo $node->nodeValue."\n", PHP_EOL; 

      }elseif($node->nodeName == 'ul'){ 
       $books = $node->getElementsByTagName('li'); 
       foreach ($books as $book) { 
        echo $book->nodeValue, PHP_EOL; 
       } 

      } 
     } 
    } 

    ?> 

輸出

text1 
list-a1 
list-a2 
list-a3 
text2 
list-b1 
list-b2 
list-b3 
text3 

要在嵌套數組的形式打印

<?php 

$html = ' 
    <p>text1</p> 
    <ul> 
     <li>list-a1</li> 
     <li>list-a2</li> 
     <li>list-a3</li> 
    </ul> 
    <p>text2</p> 
    <ul> 
     <li>list-b1</li> 
     <li>list-b2</li> 
     <li>list-b3</li> 
    </ul> 
    <p>text3</p> 
'; 

$result = array(); 

$doc = new DOMDocument(); 
$doc->loadHTML($html); 
$i = 0; 
foreach ($doc->getElementsByTagName('body')->item(0)->childNodes as $node) { 
    if ($node->nodeType === XML_ELEMENT_NODE) { 
     if($node->nodeName == 'p'){ 
      $result[$node->nodeName][$i] = $node->nodeValue; 

     }elseif($node->nodeName == 'ul'){ 
      $result[$node->nodeName][$i] = array(); 
      $books = $node->getElementsByTagName('li'); 
      foreach ($books as $book) { 
       $result[$node->nodeName][$i][$book->nodeName][] = $book->nodeValue; 
      } 

     } 
     $i++; 
    } 
} 
var_dump($result); 

?> 
+0

我希望它能解決您的問題。 – Abbas

+0

你可以做到這一點與數組我想要保存在嵌套的一個! – filip

+0

你能給出一個樣本輸出嗎? – Abbas