PHP在HTML元素上获取和设置属性 [英] PHP getting and setting attributes on HTML Elements

查看:222
本文介绍了PHP在HTML元素上获取和设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种通过php处理html元素的解决方案。
我正在阅读 http://www.php.net/manual /en/book.dom.php ,但我没有走远。

I'm looking for a solution for manipulating html elements via php. I was reading http://www.php.net/manual/en/book.dom.php but I didn't get to far.

我正在使用 iframe元素(视频嵌入代码)并尝试在回显之前对其进行修改。
我想在 src属性中添加一些参数。

I'm taking an "iframe" element ( video embed code ) and trying to modify it before echoing it. I would like to add some parameters to the "src" attribute.

基于https://stackoverflow.com/a/2386291 我能够遍历元素属性。

Based on the answer from https://stackoverflow.com/a/2386291 I'am able to iterate through element attributes.

        $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>


推荐答案

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

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

要更改URL,应首先使用 parse_url($ src),然后使用新的查询参数对其进行重建,例如:

To change the URL, you should first use parse_url($src), then rebuild it with your new query arguments, for example:

$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);

这篇关于PHP在HTML元素上获取和设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆