2013-02-21 34 views
0

這裏是一些html代碼,如何使用simplehtmldom解析html並保存到json數據?simplehtmldom解析html保存到json

<p>text1</p> 
<div> 
    <p>text2</p> 
<div> 
<ul> 
    <li>subtext1</li> 
    <li>subtext2</li> 
</ul> 
<p>text3</p> 
<div> 
    <div> 
    <p>text4</p> 
    </div> 
</div> 
<ul> 
    <li>subtext1</li> 
    <li>subtext2</li> 
</ul> 

我需要解析<ul><li><p>點頭與原來的順序,然後保存到一個JSON數據。

[ 
    { 
     "p":"text1" 
    }, 
    { 
     "p":"text2" 
    }, 
    { 
     "ul":[ 
     { 
      "li":"subtext1" 
     }, 
     { 
      "li":"subtext2" 
     } 
     ] 
    }, 
    { 
     "p":"text3" 
    }, 
    { 
     "p":"text4" 
    }, 
    { 
     "ul":[ 
     { 
      "li":"subtext3" 
     }, 
     { 
      "li":"subtext4" 
     } 
     ] 
    } 
] 

回答

0
json_encode((array) simplexml_load_string($html_input) 
1
include('simple_html_dom.php'); 
$html = str_get_html(YourContentHere); 
$data = array(); 
$count = 0; 
foreach($html->find('p') as $li) 
{ 
    $data[$count]['p'] = $li->innertext; 
    $count++; 
} 

foreach($html->find('ul') as $ul) 
{ 
    foreach($ul->find('li') as $li) 
    $data[$count]['ul'][]['li'] = $li->innertext; 
    $count++; 
} 
echo json_encode($data); 

試試這個,也許我有失誤

+0

謝謝,但這會使json數據前面的所有'p'標籤,然後li到最後。 – cj333 2013-02-21 11:51:01

0

由我自己解決,當然,我會conplete json_encode()的一部分。爲我需要的json樹。謝謝。

foreach($html->find('p, ul') as $foreach){ 
    if($foreach->tag =='p'){ 
     $out .= json_encode($foreach->plaintext); 
    }else{ 
     foreach($foreach->find('li') as $li){ 
      $out .= json_encode($li->plaintext); 
     } 
    } 
}