PHP getting and setting attributes on HTML Element

2019-06-14 18:40发布

This question already has an answer here:

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.

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.

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 />";
          }
        }

My questions are:

  1. How could I get the attribute value without iterating through all attributes of the element and checking to see if the current element is the one I'm looking for?
  2. How can I set the attribute value on the element?
  3. I prefer not to use regex for this because I would like it to be future proof. If the "iframe" tag is properly formatted, should I have any problems with this?

iframe example:

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

2条回答
来,给爷笑一个
2楼-- · 2019-06-14 19:27
// to get the 'src' attribute
$src = $frame->getAttribute('src');

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

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);
查看更多
Summer. ? 凉城
3楼-- · 2019-06-14 19:33

I don't understand why you need to iterate through the attributes to determine if this is the element you are looking for. You seem to only be grabbing the first iframe element, so I am not clear what you first question is really about.

For your second question, you just need to use setAttribute() method of DOMElement like this:

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

You shouldn't have problems parsing the HTML you have shown.

查看更多
登录 后发表回答