2013-06-12 20 views
0

我使用的是當前的功能:如何使用php調用頁面來更改/刪除字符串?

function callframe(){ 
    $ch = curl_init("file.html"); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    echo curl_exec($ch); 
    curl_close($ch); 
} 

然後調用callframe(),它出現在我的PHP頁面上。 比方說,這是file.html內容:

<html> 
<body> 

    [...] 

<td class="bottombar" valign="middle" height="20" align="center" width="1%" nowrap> 

    [...] 

<a href="link.html">Link</a> 

    [...] 

</body> 
</html> 
  • 我怎麼能刪除<td class="bottombar" valign="middle" height="20" align="center" width="1%" nowrap>線?
  • 我怎麼能刪除一個參數像高度參數,或改變對齊中心左?
  • 我怎麼會link.html前插入 'http://www.whatever.com/' 在我的A HREF

感謝您的幫助!

ps:你可能想問爲什麼我不直接改變file.html。那麼,那就沒有問題了。

+1

您需要獲得一個可以操縱HTML文檔的HTML解析器。不要試圖使用正則表達式來完成這個任務,否則你會在路上感到抱歉。你不能用正則表達式可靠地解析HTML,你將面臨悲傷和挫折。只要HTML從你的期望改變,你的代碼就會被破壞。有關如何使用已經編寫,測試和調試的PHP模塊正確解析HTML的示例,請參閱http://htmlparsing.com/php。 –

+0

看看['DOMDocument'](http://www.php.net/manual/en/class.domdocument.php)/ ['DOMElement'](http://www.php.net/manual/) en/class.domelement.php)/ ['DOMNode'](http://www.php.net/manual/en/class.domnode.php)文檔。所有你需要的東西最有可能在PHP本地(除非你使用不同的版本)。 –

回答

0

你可以把你的輸出在一個變量,並且可以使用字符串函數做你的東西

function callframe(){ 
$ch = curl_init("file.html"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$result = curl_exec($ch); 
$result = str_replace("link.html","http://www.whatever.com/link.html", $result); 
// other replacements as required 
curl_close($ch); 
} 
+0

似乎curl_setopt($ ch,CURLOPT_RETURNTRANSFER,1);不管用。該頁面不加載。 :( – dansayag

1

爲了讓您一開始,而不是僅僅呼應curl_exec,其存儲第一,所以你可以使用它:

$html = curl_exec($ch); 

現在,在加載它的DOMDocument,你就可以使用用於分析和更改:

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

現在,第一個任務(除去線),它會看起來像:

// 
// rough example, not just copy-paste code 
// 

$tds = $dom->getElementsByTagname('td'); // $tds = DOMNodeList 
foreach ($tds as $td) // $td = DOMNode 
{ 
    // validate this $td is the one you want to delete, then 
    // call something like: 
    $parent = $td->parentNode; 
    $parent->removeChild($td); 
} 

執行任何其他類型的處理爲好。

然後,最後調用:

echo $dom->saveHTML(); 
0

這是我做到了。 要更改例如選項字段(用於搜索字符串) 這會更改我的選項列表的第二個值,並將其替換爲我想要的值。

require('simple_html_dom.php'); 

$html = file_get_html('fileorurl'); 

$e = $html->find('option', 0) ->next_sibling(); 
$e->outertext = '<option value="WTR">Tradition</option>'; 

then echo $ html;

相關問題