2013-06-19 55 views
-2

我正在尋找一個通過php操作html元素的解決方案。 我在讀http://www.php.net/manual/en/book.dom.php,但我沒有走得很遠。PHP獲取和設置HTML元素的屬性

我正在使用「iframe」元素(視頻嵌入代碼)並試圖在回顯它之前進行修改。 我想添加一些參數到「src」屬性。

根據https://stackoverflow.com/a/2386291的回答,我可以迭代元素屬性。

 $doc = new DOMDocument(); 

     // $frame_array holds <iframe> tag as a string 

     $doc->loadHTML($frame_array['frame-1']); 

     $frame= $doc->getElementsByTagName('iframe')->item(0); 

     if ($frame->hasAttributes()) { 
      foreach ($frame->attributes as $attr) { 
      $name = $attr->nodeName; 
      $value = $attr->nodeValue; 
      echo "Attribute '$name' :: '$value'<br />"; 
      } 
     } 

我的問題是:

  1. 我怎麼能拿沒有通過元素的所有屬性迭代和檢查,看看是否當前元素是我找的一個屬性值?
  2. 如何設置元素的屬性值?
  3. 我不希望使用正則表達式,因爲我希望它是未來的證明。如果「iframe」標籤格式正確,我是否應該對此有任何疑問?

IFRAME例如:

<iframe src="http://player.vimeo.com/video/68567588?color=c9ff23" width="486" 
    height="273" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen> 
    </iframe> 

回答

1
// to get the 'src' attribute 
$src = $frame->getAttribute('src'); 

// to set the 'src' attribute 
$frame->setAttribute('src', 'newValue'); 

要更改URL,你應該先用parse_url($src),然後用新的查詢參數重建它,例如:

$parts = parse_url($src); 
extract($parts); // creates $host, $scheme, $path, $query... 

// extract query string into an array; 
// be careful if you have magic quotes enabled (this function may add slashes) 
parse_str($query, $args); 
$args['newArg'] = 'someValue'; 

// rebuild query string 
$query = http_build_query($args); 

$newSrc = sprintf('%s://%s%s?%s', $scheme, $host, $path, $query); 
+0

這就是要找的東西。 我很困惑,因爲phpstorm在'$ frame->'的代碼完成時沒有給我方法:'setAttribute'和'getAttribute'。所以我開始通過php在線手冊閱讀,但更加困惑。另外我想添加一個未來的參考,當你完成操作元素時,爲了回顯它,你需要這行代碼:'$ doc-> saveHTML($ frame);'php.net/manual/en /domdocument.savehtml.php –

0

我不明白爲什麼你需要遍歷屬性來確定這是否是你正在尋找的元素。你似乎只是抓住了第一個iframe元素,所以我不清楚你首先提出的問題是什麼。

關於第二個問題,你只需要使用DOMElementsetAttribute()方法是這樣的:

$frame->setAttribute($attr_key, $attr_value); 

你不應該分析你已經顯示的HTML問題。

+0

我的代碼只是一個更大代碼塊的摘錄。 –