This question already has an answer here:
- PHP Getting and Setting tag attributes 2 answers
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:
- 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?
- How can I set the attribute value on the element?
- 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>
To change the URL, you should first use
parse_url($src)
, then rebuild it with your new query arguments, for example: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 ofDOMElement
like this:You shouldn't have problems parsing the HTML you have shown.