Is there a way of appending source html into a DOMElement? Something like this:
$trElement->appendSource("<a href='?select_user=4'>Username</a>");
It would parse that fragment and then append it.
You are looking for
- DOMDocumentFragment::appendXML — Append raw XML data
Example from Manual:
$doc = new DOMDocument();
$doc->loadXML("<root/>");
$f = $doc->createDocumentFragment();
$f->appendXML("<foo>text</foo><bar>text2</bar>");
$doc->documentElement->appendChild($f);
echo $doc->saveXML();
If you don't have a reference to the document root in scope, you can always access it via the ownerDocument property of an arbitrary node:
$frag = $trElement->ownerDocument->createDocumentFragment();
$frag->appendXML("<a href='?select_user=4'>Username</a>");
$trElement->appendChild($frag);
Yes, you can do this with DOMDocument::createDocumentFragment:
$fragment = $dom->createDocumentFragment();
$fragment->appendXML('Username');
$element->appendChild($fragment);
In this case, it would be simpler to do it with a normal createElement call:
$el = $dom->createElement('a', 'Username');
$el->setAttribute('href', 'select_user=4');
$element->appendChild($el);
In each case, $element is the DOM element to which you want to append your code.
Related
I've got a php code which gets external xml file, adds something before last paragraph and saves it as new file.
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('xml.xml');
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createTextNode('<o id="1" url="link.html" price="899.00" avail="1" weight="0" stock="0" set="0" basket="0"></o>');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$xmldoc->save('sample.xml');
?>
However, I don't want to lose XML signs like " <> ". What should I use instead of createTextNode? Because by now I've got a code like this:
<o id="1" url="link.html" price="899.00" avail="1" weight="0" stock="0" set="0" basket="0">
DOMDocument::createTextNode() does exactly that it creates a node containing text. It does not loose the special characters - they will be encoded as entities for the serialization.
Here are other methods like DOMDocument::createElement() to create an element node and DOMElement::setAttribute() to set attributes on an element node.
If you have an XML fragment as a string literal, here is a node type that can consume it. The DOMDocumentFragment.
$document = new DOMDocument();
$root = $document->appendChild($document->createElement('foo'));
$fragment = $document->createDocumentFragment();
$fragment->appendXml('<p>some text</p>');
$root->appendChild($fragment);
echo $document->saveXml();
Document fragments are kind of virtual nodes, the are a list of nodes with a single node as a container so that they can be passed to the DOM methods. Be careful using DOMDocumentFragment:appendXml() or you might open yourself to HTML/XML injections.
You are searching createElement.
<?php
$newElement = $xmldoc->createTextNode('o');
$newElement->setAttribute("url", "link.html");
You can then add attributes to match with your example.
See setAttribute. createTextNode creates only a text node, no XML. createElement, creates an XML element.
Say I have an html file that I have loaded, I run this query:
$url = 'http://www.fangraphs.com/players.aspx';
$html = file_get_contents($url);
$myDom = new DOMDocument;
$myDom->formatOutput = true;
#$myDom->loadHTML($html);
$anchor = $xpath->query('//a[contains(#href,"letter")]');
That gives me a list of these anchors that look like the following:
Aa
But I need a way to only get "players.aspx?letter=Aa".
I thought I could try:
$anchor = $xpath->query('//a[contains(#href,"letter")]/#href');
But that gives me a php error saying I couldn't append node when I try the following:
$xpath = new DOMXPath($myDom);
$newDom = new DOMDocument;
$j = 0;
while( $myAnchor = $anchor->item($j++) ){
$node = $newDom->importNode( $myAnchor, true ); // import node
$newDom->appendChild($node);
}
Any idea how to obtain just the value of the href tags that the first query selects?? Thanks!
Use:
//a/#href[contains(., 'letter')]
this selects any href attribute of any a whose string value (of the attribute) contains the string "letter" .
Your XPath query is returning attributes themselves (i.e., DOMAttr objects) rather than elements (i.e., DOMElement objects). That's fine, and that seems to be what you want, but appending them to the document is the problem. A DOMAttr is not a standalone node in the document tree; it's associated with a DOMElement but is not a child in the usual sense. Thus, directly appending a DOMAttr to the document is invalid.
From the W3C specs:
Attr objects inherit the Node interface, but since they are not actually child nodes of the element they describe, the DOM does not consider them part of the document tree. . . . The DOM takes the view that attributes are properties of elements rather than having a separate identity from the elements they are associated with
Either associate the DOMAttr with a DOMElement and append that element, or pull out the DOMAttr's value and use that as you wish.
To just append its plain text value, use its value in a DOMText node and append that. For example, change this line:
$newDom->appendChild($node);
to this:
$newDom->appendChild(new DOMText($node->value));
try this..
$xml_string = 'your xml string';
$xml = simplexml_load_string($xml_string);
foreach($xml->a[0]->attributes() as $href => $value) {
$myAnchorsValues[] = $value;
}
var_dump($myAnchorsValues);
I'm using PHP/Zend to load html into a DOM, and then I get a specific div id that I want to modify.
$dom = new Zend_Dom_Query($html);
$element = $dom->query('div[id="someid"]');
How do I modify the text/content/html displayed inside that $element div, and then save the changes to the $dom or $html so I can print the modified html. Any idea how to do this?
Zend_Dom_Query is tailored just for querying a dom, so it doesn't provide an interface in and of itself to alter the dom and save it, but it does expose the PHP Native DOM objects that will let you do so. Something like this should work:
$dom = new Zend_Dom_Query($html);
$document = $dom->getDocument();
$elements = $dom->query('div[id="someid"]');
foreach($elements AS $element) {
//$element is an instance of DOMElement (http://www.php.net/DOMElement)
//You have to create new nodes off the document
$node = $document->createElement("div", "contents of div");
$element->appendChild($node)
}
$newHtml = $document->saveXml();
Take a look at the PHP Doc for DOMElement to get an idea of how you can alter the dom:
http://www.php.net/DOMElement
I'd like to search for nodes with the same node name in a SimpleXML Object no matter how deep they are nested and create an instance of them as an array.
In the HTML DOM I can do that with JavaScript by using getElementsByTagName(). Is there a way to do that in PHP as well?
Yes use xpath
$xml->xpath('//div');
Here $xml is your SimpleXML object.
In this example you will get array of all 'div' elements
$fname = dirname(__FILE__) . '\\xml\\crRoll.xml';
$dom = new DOMDocument;
$dom->load($fname, LIBXML_DTDLOAD|LIBXML_DTDATTR);
$root = $dom->documentElement;
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('cr', "http://www.w3.org/1999/xhtml");
$candidateNodes = $xpath->query("//cr:break");
foreach ($candidateNodes as $child) {
$max = $child->getAttribute('tstamp');
}
This finds all the BREAK nodes (tstamp attr) using XPath ...
Only on DOMDocument::getElementsByTagName,
however, you can import/export SimpleXML into DOMDocument,
or simply use DOMDocument to parse XML.
Another answer mentioned about Xpath,
it will return duplication of node, if you have something like :-
<div><div>1</div></div>
Is there a way to create a node that has mixed XML content in it with the PHP DOM?
If I understood you correctly you want something similar to innerHTML in JavaScript. There is a solution to that:
$xmlString = 'some <b>mixed</b> content';
$dom = new DOMDocument;
$fragment = $dom->createDocumentFragment();
$fragment->appendXML($xmlString);
$dom->appendChild($fragment);
// done
To sumarize. What you need is:
DOMDocument::createDocumentFragment()
DOMDocumentFragment::appendXML()
Although you didn't asked about it I'll tell you how to get the string representation of a DOM node as opposed to the whole DOM document:
// for a DOMDocument you have
$dom->save($file);
$string = $dom->saveXML();
$dom->saveHTML();
$string = $dom->saveHTMLFile($file);
// For a DOMElement you have
$node = $dom->getElementById('some-id');
$string = $node->C14N();
$node->C14NFile($file);
Those two methods are currently not documented.