2011-03-04 122 views
0

我有一個解析URL的問題。我想用dom來做,但我不知道從哪裏開始。我只想從下面的代碼解析src。任何想法都會非常感謝你。php解析與dom

<script type="text/javascript" src="http://website.com/?code-ajax&cd=1145040425"></script> 

回答

1
$doc = new DOMDocument(); 
$doc->loadXML($xml); 
$src = $doc->documentElement->getAttribute('src'); 

的XPath例如,使用遠程文件

$doc = new DOMDocument(); 
$doc->loadHTMLFile($url); 
$xpath = new DOMXpath($doc); 

// Retrieve collections of script nodes 
$allScripts = $xpath->query('//script'); 
$headScripts = $xpath->query('/html/head/script'); 
$bodyScripts = $xpath->query('/html/body/script'); 

// Get all scripts who's src attribute starts with "http://website.com" 
$websiteScripts = $xpath->query('//script[starts-with(@src, "http://website.com")]'); 
if ($websiteScripts->length) { 
    // contains one or more matches 
    $src = $websiteScripts->item(0)->getAttribute('src'); 
} 
+0

怪異,不能發佈包含腳本標籤(企業防火牆也許)任何東西。假設'$ xml'變量包含你的問題中的字符串 – Phil 2011-03-04 01:48:23

+0

@PhilBrown如果我想用這個外部網頁怎麼辦 – sabrina 2011-03-04 02:53:37

+0

@sabrina你可以使用'DOMDocument :: loadXMLFile()'或'DOMDocument :: loadHTMLFile()'取決於頁面的文檔類型。您還需要更改到達腳本節點的方式,因爲您將處理整個頁面而不僅僅處理一個節點。你應該編輯你的問題,以更好地反映你想要做什麼 – Phil 2011-03-04 02:57:21

1

我最喜歡的解決方案是simplehtmldom PHP庫,它是很多簡單的比PHP的本地解決方案中使用;我從經驗中這樣說。它的語法和用法與jQuery相似。

你可以使用它像這樣

include('lib/simple_html_dom.php'); 
$html = str_get_html('<script type="text/javascript" src="http://website.com/?code-ajax&cd=1145040425"></script>'); 
$scriptsrc = $html->find('script',0)->src; 
+0

+1對於SimpleHTMLDom的同伴用戶 – drudge 2011-03-04 01:57:00

1

使用SimpleHTMLDom庫:

<?php 
    // include the SimpleHTMLDom library 
    include('lib/simple_html_dom.php'); 

    // our input string 
    $input = '<script type="text/javascript" src="http://website.com/?code-ajax&cd=1145040425"></script>'; 

    // create our Object. If reading from a file, use: file_get_html('/path/to/file'); 
    $doc = str_get_html($input); 

    // find the first <script> tag, and echo its 'src' attribute. 
    // -- note: calling this with find('script') returns an array 
    echo $doc->find('script',0)->src; 
?> 
+0

這是PHP中最好的事情之一,與Hip Hop – Sandwich 2011-03-04 06:57:50