Re: [PHP] XML Get Value of Node DOMXPath
Stephen Alistoun wrote: Hello all, Need help to get the value of the node. We know how to get the value of the city , item and itemPrice nodes below. How do we get the value of NumberOfRooms? $hotelElements = $xpath->query( '', $searchReponseElement ); foreach( $hotelElements as $hotelElement ) { $city = $xpath->query( 'City' , $hotelElement ); $item = $xpath->query( 'Item' , $hotelElement ); $itemPrice = $xpath->query( 'ItemPrice' , $hotelElement ); $confirmation = $xpath->query( 'Confirmation' , $hotelElement ); } Here is an example of the XML Response: 4 Code="SB" NumberOfRooms="1" /> Code="TB" ExtraBed="true" NumberCots="1" NumberOfExtraBeds="2" NumberOfRooms="1 SharingBedding="true" /> Thanks You can do it in a number of ways. $rooms = $xpath->query('/Hotel/HotelRooms/HotelRoom'); /* Via DOMElement */ foreach ($rooms AS $room) { echo $room->getAttribute('NumberOfRooms') . "\n\n"; } /* Via XPath */ foreach ($rooms AS $room) { $numrooms = $xpath->evaluate('number(./@NumberOfRooms)', $room); echo $numrooms . "\n\n"; } Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Freeing memory for DOMDocument
Nathan Rixham wrote: Jesús Enrique Muñoz Fernández wrote: Maybe you could find and answer here: *http://drupal.org/node/81037 Some people have the same problem, i was this trouble in the past and i fix it increasing the *memory_limit *in php.ini file* Anyway read the posts in the url that i wrote. > To: php-general@lists.php.net; jcbo...@yahoo.com > Date: Wed, 7 Jan 2009 15:21:50 + > From: nrix...@gmail.com > CC: php-general@lists.php.net > Subject: [PHP] Re: Freeing memory for DOMDocument > > Christoph Boget wrote: > > I'm running through a large dataset and am generating/manipulating XML > > documents for each record. What's happening is that after a while, I > > get a fatal error saying: > > > > Fatal error: Allowed memory size of 167772160 bytes exhausted (tried > > to allocate 32650313 bytes) > > > > Each XML file I generate (an manipulate) can range from just a few > > megs to upwards of 35 megs. Judging from the error above, it looks > > like the memory for the DOMDocument objects I instantiate is not > > getting freed; it just continues to stay in memory until the memory is > > completely exhausted. The method (in my object) I am using to > > instantiate a new DOMDocument is as follows: > > > > protected function createCleanDomDocument() > > { > > /* > > if(( isset( $this->oDomXPath )) && ( !is_null( $this->oDomXPath ))) > > { > > unset( $this->oDomXPath ); > > } > > > > if(( isset( $this->oDomDocument )) && ( !is_null( $this->oDomDocument ))) > > { > > unset( $this->oDomDocument ); > > } > > */ > > $this->oDomDocument = new DOMDocument( '1.0', 'iso-8859-1' ); > > $this->oDomXPath = new DOMXpath( $this->oDomDocument ); > > } > > > > which is used in both the constructor of my object and in a few other > > places. I would think that when the new DOMDocument is instantiated, > > the memory used for the old value would get freed. As you can see, > > I've even tried to unset the variables but that doesn't seem to help > > matters much, either. > > > > Does anyone know how (or even if) I can explicitly free the memory > > used for the DOMDocument? Any help/advice would be greatly > > appreciated! > > > > thnx, > > Christoph > > I've had exactly the same problem and couldn't find a way around it; > even after unsetting every variable in my scripts inside a for/while > loop; in the end I opted for a CLI script which opened worker threads > then killed/restarted them when memory usage was X. > Just because.. I'm going to write out my thoughts on this and see if we can come to any kind of fixed bug or solution. The issue is that memory assigned to DOMDocuments is not being freed correctly. The job of freeing memory falls to the garbage collection; which implements the following algorithm: http://www.research.ibm.com/people/d/dfb/papers/Bacon03Pure.pdf (root buffer size of 1) AFAIK a variable becomes a candidate for gc when it is no longer required (unset and no references to it?) because of the way we use domdocument often we have many variables referencing existing or created nodes within the document; as well as xpath and suchlike; thus it stands to reason that unless all of these are also unset the DOMDocument will not be caught by gc. first test then is to check that all variables that even sniff at the DOMDocument (or nodes within) are unset. technically I'd guess that a script that loads an xml document in to a DOMDocument, then unsets it on a for loop should never grow the used memory. I'm going to write a little test script to prove this in a mo. Memory is freed correctly with DOM objects. While a DOMDocument object is destroyed once there are no more references to it, the underlying XML document structure is only destroyed once all DOMNode objects that are members of the document are destroyed as well. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: php get rss tag using DOM
Morris wrote: I know rss_php, but it doesn't fit my solution. Is anyone able to help me with my question? thx 2009/2/8 Nathan Rixham Morris wrote: Hi, I am trying to write a programme to read a rss xml file. ... ... scan anyone tell me how to get the url attribute? I wrote some codes similar: $doc = new DOMDocument; $doc->load($myFlickrRss); $r = $doc->getElementsByTagName('media:content'); for($i=0;$i<=$r->length;$i++) { // help here } use http://rssphp.net/ you can view the source online and it's all done using DOMDocuments :) First off, you should be using getElementsByTagNameNS since you are working with a namespaced document. I am assuming its a Yahoo Media RSS feed, so you would get the elements via: $r = $doc->getElementsByTagNameNS("http://search.yahoo.com/mrss/";, "content"); Then to output the url attribute value: foreach ($r AS $elem) { echo $elem->getAttribute("url") . "\n"; } Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] How to prevent DomDocument from adding a !DOCTYPE.
Mathijs van Veluw wrote: Roman Neuhauser wrote: # [EMAIL PROTECTED] / 2007-01-16 15:37:09 +0100: Im using DomDocument currently and i realy want to prevent it from adding the !DOCTYPE and mabye even and etc.. Is this possible and how? Doesn't DOMDocument *require* DTD? I thought it's either that or a "document fragment" (which is probably what you're looking for). And how should i do this? Do you have any example avelable? A DTD is not required and is not automatically added to XML documents. Tags are also not automatically added either (using loadHTML methods is excluded from this statement) so not sure exactly what you are trying to do here or running into. Are you just trying to serialize a DOMDocument? is a perfectly well-formed document (though inclusion of xml declaration is *highly* recommended). Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: How to prevent DomDocument from adding a !DOCTYPE.
Mathijs wrote: I have some HTML content: Testing ØøÅå_^{}\[~]|[EMAIL PROTECTED]"#¤%&'()*+,ÖÑܧ¿äöñüà-./:;<=>?¡Ä Now i need to parse the HTML by getting all the class and id attributes and replace them with something else, and after that return the modified HTML. If this were XHTML or you were working with complete HTML documents, then you would have a shot. Being HTML snippets, you are going to run into problems (different encodings, possibility of entities, etc..) - all of which need to be handled. You could probably hack the snippet a bit to "create" a full HTML document, but there's still no guarantee it will work correctly between different snippets. On top of that, unlike working with XML, there is no way to output a subtree of HTML. You would need to use the XML serialization routines, which would most likely change the structure of your document (it would be XHTML compliant now). Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Extending DOMNode
Eli wrote: registerNodeClass('DOMNode','MyDOMNode'); $dom->loadXML(''); echo $dom->firstChild->v; #<-- not outputs 10 ?> But I get the notice: PHP Notice: Undefined property: DOMElement::$v in ... I want the extension to be valid for all DOM nodes that are derived from DOMNode, such as DOMElement, DOMAttr, DOMNodeList, DOMText, etc... I try not to extend all the classes one by one. Due to the internals of the DOM extension, you need to register the class types that are actually instantiated and not the underlying base DOMNode class. Unfortunately in your case this means you need to register all of those classes separately. $dom->registerNodeClass('DOMElement','MyDOMNode'); $dom->registerNodeClass('DOMAttr','MyDOMNode'); $dom->registerNodeClass('DOMText','MyDOMNode'); ... Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Extending DOMNode
Eli wrote: Rob Richards wrote: Due to the internals of the DOM extension, you need to register the class types that are actually instantiated and not the underlying base DOMNode class. Unfortunately in your case this means you need to register all of those classes separately. $dom->registerNodeClass('DOMElement','MyDOMNode'); $dom->registerNodeClass('DOMAttr','MyDOMNode'); $dom->registerNodeClass('DOMText','MyDOMNode'); ... Not good... :-( registerNodeClass('DOMElement','MyDOMNode'); ?> PHP Fatal error: DOMDocument::registerNodeClass(): Class MyDOMNode is not derived from DOMElement. So I have to extend DOMElement and register MyDOMElement. But all my nodes should be also based on MyDOMNode. Problem is that in PHP you can only extend one class in a time, so you cannot build your own class-tree which extends a base class-tree of DOM. :-/ Ooops. Wasn't thinking when I wrote that. Yup, you will need to extend every one of the node types separately and then register those classes. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] DOM Element default ID attribute
Eli wrote: Let me try to be more clear.. Say you got the element , then I want the DOMDocument to automatically convert the 'key' attribute to an ID-Attribute, as done with DOMElement::setIdAttribute() function. The ID-Attribute is indexed and can be quickly gotten via DOMDocument::getElementById() function. I'm trying to avoid looping on all nodes overriding the importNode() and __construct() methods of DOMDocument. Add a DTD to the document defining your attribute as an ID. $xml = << ]> This is Peter This is Sam This is Mike EOXML; $dom = new DOMDocument(); $dom->loadXML($xml); if ($elem = $dom->getElementByID("sam")) { print $elem->textContent; } else { print "Element not found"; } Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: SimpleXML & libxml options (XInclude)
Ben Roberts wrote: Thanks Rob. That works. And it appears to work flawlessly if you subsequently convert it back to a SimpleXML object too: $xml = new SimpleXMLElement($xml_file, 0, true); $dom = dom_import_simplexml($xml); $dom->ownerDocument->xinclude(); $xml = simplexml_import_dom($dom); Dump($xml); No need to even do that. The document is the same document (zero copy which is why going back and forth is efficient), so when its changed by the xinclude call, it is reflected in $xml already. Only reason you would need to do conversions back and forth is if you need specific nodes that might have been added/changed by the other extension. Here you are using the same root element and dont have to worry about losing any child references you might already have, so its a wasted call. Is it likely that this will be supported directly by SimpleXML in future versions of PHP? Unless the libxml2 parser in SimpleXML can take advantage of the option, an XInclude method is not going to be added to SimpleXML. For things like that, and full XPath support, etc.., you need to interop with DOM so SimpleXML can be kept simple. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: SimpleXML & libxml options (XInclude)
Ben Roberts wrote: So really when you perform: $dom = dom_import_simplexml($xml); the $dom object is really created by taking a reference to the $xml object rather than copying it? i.e. (I know this isn't real code) $dom = dom_import_simplexml(& $xml); Not exactly, but the idea is along those lines. What is happening is that $dom (DOMElement in this case) now points to the same libxml2 structure as does $xml (SimpleXMLElement). So now when you modify the structure of the document with one, it is reflected by the other because they are in the same document. This also means that it is possible that objects can become invalid by changes made in the other extension. $sxe = new SimpleXMLElement("text"); $sxechild = $sxe->child->inner[0]; $dom = dom_import_simplexml($sxe); $dom->removeChild($dom->firstChild); var_dump($sxechild); PHP Warning: var_dump(): Node no longer exists in /home/rrichards/temp.php on line 8 object(SimpleXMLElement)#3 (0) { } This shows that $sxechild is still an SimpleXMLElement, but warnings are issues that the node it refers to in the document no longer exists. Although I doubt someone use the code above, it is the smallest piece of code I could write to demonstrate the possibility. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] DOMDocument::schemaValidate() -> libxml_get_errors()
Tijnema ! wrote: On 4/5/07, Sébastien WENSKE <[EMAIL PROTECTED]> wrote: Yes it's exactly the error, see the output : DOMDocument::schemaValidate() Generated Errors! Error 1871: Element 'EcheanceRMC': This element is not expected. in file:///D%3A/wamp/www/XML%20Validator/xml/Edit4.xml on line 65535 <- that's wrong the real line number is upper [...] ... I don't think it has to do with integer, unless you're running in 16bit mode.. (PHP can't even run under 16bit i guess..). An integer could a lot more. I think there are 2 options that make this error: 1) The libxml library itself doesn't support it. 2) The PHP bindings with the libxml don't support it. In the first case you would need to contact the libxml authors, in the second case, you might want to write a patch that fixes it :) It is due to the structure in libxml2 (the line number in this case is defined as unsigned short). This has been brought up before and wont be changing as it would break API/AB compatibility. There really is little you can do here. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] php 5 soap question
__getTypes() and __getFunctions() are your friends. They tell you alot about the functions and structure of parameters and return types. Rob Hurst, Michael S. wrote: I would have to get approval before I can do that. I can probably post a portion of the wsdl but not sure that it would be something that is wanted to be made public in its current form. I will need to find out. Mike From: Nathan Nobbe [mailto:[EMAIL PROTECTED] Sent: Friday, September 28, 2007 2:27 PM To: Hurst, Michael S. Cc: php-general@lists.php.net Subject: Re: [PHP] php 5 soap question can you post the url of the wsdl ? -nathan On 9/28/07, Hurst, Michael S. <[EMAIL PROTECTED]> wrote: I am trying to find out how to use php 5 to access a wsdl with the following structure. How do you send parameters to the service if the wsdl is like the following. - - - - - It is similiar but I can find nothing that addresses this sort of structure and I am at a loss as how to send vars to the request using php 5. I have looked for several days and cannot figure this out. I didn't know if there was a page you could direct me to. Mike Hurst [EMAIL PROTECTED] -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Compile - libxml2
Hi Benjamin, You really need to read the response more carefully. Benjamin Dupuis wrote: I've opened a bug report on bug.php.net, Compiling PHP in 5.2.2 is working with my libxml2, but not in 5.2.4 (and 5.2.5) but developpers say me that's not a bug : I must use XML2_DIR instead of XML_DIR, But when using configure, it say me : use libxml-dir for libxml2 using libxml2-dir is not working, in 5.2.2 and 5.2.4 using libxml-dir is working in 5.2.2 but no 5.2.4 libxml2-dir isn't an existing variable in the configuration script. XML_DIR=/opt/freeware/libxml2/${XML_VERSION} That's what's defined. --with-libxml-dir=${XML2_DIR} \ That's what your using. Where is XML2_DIR coming from? Your path only shows XML_DIR being defined. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: DOM - Question about \0
dav wrote: Hi, I have question about \0 character with DOM : What to do with the character \0 ? encode this character to obtain : ? or skip the character with str_replace("\0", '', $cdata) ? CDATA is raw data and why it doesnt get magically encoded. If you remove the character then you are altering the raw data - also not a good thing typically. What is the best thing to do ? i like to conserve the \0 because is a blob data Jabber is how to transmit binary ? Never use CDATA sections. blob data should always be base64 encoded (or some other encoding). The data can then be transmitted in a regular element. Note that it is possible that your blob data can contain the following sequence of characters "]]>" which would effectively terminate the CDATA block even though there really is more data. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: XML DOM problem with getAttribute(string)
Borden Rhodes wrote: I'm having a pig of a time trying to figure this one out: I have an XHTML document which I've loaded into a DOMDocument because I want to add more tags to it. However, since I live in a bilingual country, I want to get the document's xml:lang attribute so I know what language to add my new tags in. I want to write $lang = $page->documentElement->getAttribute('xml:lang'); OR $lang = $page->documentElement->getAttributeNS('xml', 'lang'); but both of these return empty strings, indicating that it cannot find the xml:lang attribute. And yet, $page->documentElement->hasAttributes() returns true and $page->documentElement->attributes->getNamedItem('xml:lang')->nodeValue; works correctly. So why doesn't my preferred code? The xml prefix is bound to the http://www.w3.org/XML/1998/namespace namespace. $lang = $page->documentElement->getAttributeNS('http://www.w3.org/XML/1998/namespace', 'lang'); Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: XML DOM problem with getAttribute(string)
You might want to put a link to a complete example because $page->documentElement->getAttributeNS('http://www.w3.org/XML/1998/namespace', 'lang'); is how you access it. Rob [EMAIL PROTECTED] wrote: Thank you, Rob, Unfortunately, that didn't work, either (though I'll keep it in mind). The returned string is still empty. I also unsuccessfully fetched the 'xmlns' attribute using getAttribute(). Interestingly, although hasAttributes(void) returns true, hasAttribute('xmlns'), and hasAttribute(' xml:lang') both return false. On 11/06/2008, Rob Richards <[EMAIL PROTECTED]> wrote: Borden Rhodes wrote: I'm having a pig of a time trying to figure this one out: I have an XHTML document which I've loaded into a DOMDocument because I want to add more tags to it. However, since I live in a bilingual country, I want to get the document's xml:lang attribute so I know what language to add my new tags in. I want to write $lang = $page->documentElement->getAttribute('xml:lang'); OR $lang = $page->documentElement->getAttributeNS('xml', 'lang'); but both of these return empty strings, indicating that it cannot find the xml:lang attribute. And yet, $page->documentElement->hasAttributes() returns true and $page->documentElement->attributes->getNamedItem('xml:lang')->nodeValue; works correctly. So why doesn't my preferred code? The xml prefix is bound to the http://www.w3.org/XML/1998/namespace namespace. $lang = $page->documentElement->getAttributeNS('http://www.w3.org/XML/1998/namespace', 'lang'); Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] DOM Question. No pun intended.
[EMAIL PROTECTED] wrote: Rob, I wasn't aware that that would work. I mean I suppose it should, but basically this is what I'm doing: 1) Create a new DOMDocument 2) DOMDocument->loadHTML() 3) find the elements I want with getElementsByTag() then finding the one with the correct attributes . . .at this point, I need the equivalent of DOMDocument->saveHTML() so that it outputs the *exact* html content. Are you saying that saveXML() will do what I want it to do; tags and all? It is the best option, though in reality there may not be a way to do this exactly as you want due to HTML not having to be valid XML. By exact, unless the input is valid XHTML, loadHTML is going to cause the HTML to be fiexed to be proper XML, so using $doc->saveXML($node) you will get the serialized of the element as it was created when loading the HTML (this includes any "fixes" the parser may have made. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: simplify DOM api
Andreas Korthaus wrote: I think this should be OK, or shouldn't I do it this way? Both ways are perfectly acceptable and all up to personal preference. In fact, to support the way you are doing it was one of the reasons why DOM classes were allowed to be extended. Perhaps you have seen that I've used a "xml_entity_encode()" function. This function works like htmlspecialchars(), but replaces ' with ' and not '. Or do all of you use htmlspecialchars()? Does it work with Unicode strings? I typically use htmlspecialchars() and remember that you are going to have to work with UTF-8, which is compatible with htmlspecialchars(), when editing a tree. You can also look at using xmlwriter, when creating serialized trees, that automatically does escaping for you. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: simplify DOM api
Andreas Korthaus wrote: Rob Richards wrote: You can also look at using xmlwriter, when creating serialized trees, that automatically does escaping for you. Hm, AFAIK latest xmlwriter versions provide an OO API. Do you know about any documentation for it? I will try to add some time permitting. The only code I've seen so far is: http://cvs.php.net/viewcvs.cgi/pecl/xmlwriter/examples/xmlwriter_oo.php?view=markup&rev=1.1.2.2 And that's not too much (but promising) ;-) Or do you know about some more complex examples? I do, but none are available anywhere public. You should also look at the test cases that have been written for it: http://cvs.php.net/viewcvs.cgi/php-src/ext/xmlwriter/tests/ These have cases for both OO and procedural. Btw. I need to validate my created documents against an XML schema, I doubt this is possible with xmlwriter. Not unless you re-load the document using a validating parser. I had just thrown that extension out there in the event you were just creating a serialized tree. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] I am not able to download domxml for PHP5
Oz wrote: For some reason my PHP5 does not have DOM. ( I have the version that comes with fedora core 5). Is there a way to activate it. -thanks Oz You need to install the php-xml rpm to get the xml extensions (dom, xsl, xmlwriter and xmlreader). Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: DOMElement->setAttribute() loops forever (node_list_unlink bug?)
Riku Palomäki wrote: Hello, I'm having problems with DOMElement->setAttribute() -method with my php script. I stripped down the code to this: -- $doc = new DOMDocument(); $doc->resolveExternals = true; $doc->loadXml('http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";>'); $root = $doc->getElementsByTagName('a')->item(0); $root->setAttribute('b', '>'); $root->setAttribute('b', ''); // This will never be executed echo "done\n"; -- Can you please bug this (no need for the backtrace), so I don't forget it. I see the problem but will take me a day or two to get around to fix. As a work around for now you can do: $root->setAttributeNode(new DOMAttr('b', '>')); $root->setAttribute('b', ''); Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Bug in XMLWriter?
Expected behavior. See comments within code snippet. D. Dante Lorenso wrote: I am using XMLWriter with PHP 5.1.4 and find that it doesn't behave as I expect. I am under the impressing that until I call 'endElement', I should be free to continue adding attributes to an opened element regardless of whether I have already added elements or text below it. Look at this sample code: openMemory(); // start new element and add 1 attribute $XML->startElement("a"); $XML->writeAttribute("href", "http://www.google.com";); // add a text node $XML->text("Google"); Here you just closed the starting element tag and moved into content. // add another attribute (DOES NOT WORK) $XML->writeAttribute("target", "_blank"); If you check the return value (FALSE), you will see it failed. The writer is positioned within element content so cannot write an attribute. Attributes must be written while still positioned within the element's start tag. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: Bug in XMLWriter?
D. Dante Lorenso wrote: Rob Richards wrote: Expected behavior. See comments within code snippet. D. Dante Lorenso wrote: I am using XMLWriter with PHP 5.1.4 and find that it doesn't behave as I expect. I am under the impressing that until I call 'endElement', I should be free to continue adding attributes to an opened element regardless of whether I have already added elements or text below it. Look at this sample code: openMemory(); // start new element and add 1 attribute $XML->startElement("a"); $XML->writeAttribute("href", "http://www.google.com";); // add a text node $XML->text("Google"); Here you just closed the starting element tag and moved into content. So adding a text node closes the starting tag? That shouldn't happen. Uhm, so where's the text supposed to go? Seems to me that this is non-intuitive. I would expect that until I call 'endElement' that the node is still constructible. Internally it should work something like DOM where the node is not 'serialized' to xml tag form until the endElement is called. That way, attributes could still be defined even after 'text' nodes were appended. You are missing the point of xmlWriter. It should happen. It provides a forward only, non-cached means of writing to a stream. There are no "nodes" or "trees" here. Calling endElement simply instructs the writer to close any open content or attributes and finally the currently opened element. For your example code, just write all attributes prior to adding any element content; otherwise you really want a tree based API like DOM or SimpleXML where you can move backwards. In any case, the behavior will not change. The behavior is defined in the XMLTextWriter class in C#, from which XMLWriter is based on. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Replacing text of a DOM text node
Hi Frank, Frank Arensmeier wrote: > Jochem, thank you for your input! > > So, right now I am able to access all text nodes by e.g. > > $nodeElement -> parentNode -> childNodes -> item(0); -> returns Lenght, > Width and so on > $nodeElement -> parentNode -> childNodes -> item(1); -> is empty > $nodeElement -> parentNode -> childNodes -> item(2); -> returns mm, kg ... > > and so on. Or is there an easier way? When trying to acces the items by > > ($nodeElement containing text nodes) > > $nodeElemtent -> item(0); > > I get the following error message: Call to undefined method > DOMText::item()... Only a nodelist and namenodemap has the item() method. You could also do something like the following - note that manually walking the tree is much faster than iterating a nodelist - (there are also many different variations of this code depending upon what you need to do with the subtree): $node = $nodeElement->parentNode->firstChild; while ($node) { /* only process text or element nodes here */ if ($node->nodeType == XML_TEXT_NODE) { $node->nodeValue = 'New text content'; /* modify text content */ } else if ($node->nodeType == XML_ELEMENT_NODE) { /* node is element - process its subtree or move on i.e.: */ if ($node->hasChildNodes()) { foreach ($node->childNodes AS $child) { /* process child nodes here */ } } } $node = $node->nextSibling; } > > BTW, is there an easy way to get the total amount of items in a curent > node? count ( $nodeElement -> parentNode -> childNodes ) always returns > 1. For now the only solution I know of is looping through the > nodeElements (e.g. foreach ( $nodeElement as $value ) and have a counter > inside the loop. $count = $nodeElement->parentNode->childNodes->length; This property is only available from a nodelist or namednodemap. > > Thank you so far. > /frank > > ps. I am desperately looking for some good sites covering the PHP DOM > functions. On www.php.net/dom there are barely some examples. And on > www.zend.com I only found one article with very, very basic examples. > Any ideas/suggestions are more than welcome. ds. You can pretty much search for examples from any DOM implementation since its a standard (not too difficult to go from one language to another when using DOM). For PHP specific ones, there are a number of tests in the CVS repository that demonstrate much of the functionality: http://cvs.php.net/viewcvs.cgi/php-src/ext/dom/tests/ One particular test that uses a good amount of the API (though the basic functions) is dom001.phpt: http://cvs.php.net/viewcvs.cgi/php-src/ext/dom/tests/dom001.phpt?view=markup&rev=1.4 Rob -- [EMAIL PROTECTED] author of Pro PHP XML and Web Services from Apress -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: XPath avg(), min(), max() functions not found
Hi Alex, Alex wrote: Hi all. I'm trying to use XPath avg(), min() and max() functions without success. Others functions like count() or sum() works correctly. Here is the code I'm using (PHP 5.1): 25 7 50 3 '; $xml_doc = new DOMDocument(); $xml_doc->loadXML($xml_str); $xpath = new DOMXPath($xml_doc); $cards_avg = $xpath->evaluate("avg(//card/[EMAIL PROTECTED]'visits'])"); var_dump($cards_avg); $cards_sum = $xpath->evaluate("sum(//card/[EMAIL PROTECTED]'visits'])"); var_dump($cards_sum); ?> min(), max() and avg() don't exist in XPath 1.0 which is the version implemented in libxml2. You need to calculate these yourself. For example: /* Find the average */ $cards_avg = $xpath->evaluate("sum(//card/[EMAIL PROTECTED]'visits']) div count(//card/[EMAIL PROTECTED]'visits'])"); var_dump($cards_avg); $cards_sum = $xpath->evaluate("sum(//card/[EMAIL PROTECTED]'visits'])"); var_dump($cards_sum); /* Find lowest visits */ $cards_min_nodes = $xpath->query("//card/[EMAIL PROTECTED]'visits']/text()"); $min = NULL; foreach ($cards_min_nodes AS $node) { $val = (int)$node->nodeValue; if (is_null($min) || $min > $val) { $min = $val; } } print 'Minimum Visits: '.$min."\n"; /* Find maximum visits */ $cards_max_nodes = $xpath->query("//card/[EMAIL PROTECTED]'visits']/text()"); $max = NULL; foreach ($cards_max_nodes AS $node) { $val = (int)$node->nodeValue; if (is_null($min) || $max < $val) { $max = $val; } } print 'Maximum Visits: '.$max."\n"; Rob -- [EMAIL PROTECTED] author of Pro PHP XML and Web Services from Apress -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] transform RDF to HTML via XSL and PHP
Mario Pavlov wrote: nope it doesn't work like this still the same result I think the problem is in the way that I'm accessing the elements how exactly this should be done ?... Its due to default namespaces in the feed. The item elements and its child elements are in the default namespace: http://my.netscape.com/rdf/simple/0.9/ You need to declare this namespace with a prefix in order to access the elements within the stylesheet (same as using XPath). i.e. the following stylesheet uses the prefix rdf9 for that namespace. http://www.w3.org/1999/XSL/Transform"; xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"; xmlns:rdf9="http://my.netscape.com/rdf/simple/0.9/";> Rob -- [EMAIL PROTECTED] author of Pro PHP XML and Web Services from Apress -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: [PHP-XML-DEV] Re: [PHP] PHP5: ext/dom - set namespace of node manually
> Porting the setNamespace function to PHP5 would be nice. Another solution > could be the possibility to append a namespace-node (is the > domnamespacenode class currently used by any functions?) or the > setAttribute checks wether some "xmlns"/"xmlns:" attribute is set and > updates namespaceUri itself... would be more W3C standard compliant. The namespace node isnt really used with any functions. It is also a "special" node as its not a standard node type in libxml. Via the specs, it doesnt really exist, but it can be returned via xpath, which is why dom manipulates the libxml namespace into a returnable type, which a few of the properties are allowed to work with it (otherwise either dom would either have to prevent xpath from returning it or let the system crash when its returned - neither of these options was acceptable - thus this special node). As far as setAttributeNS goes. This function actually does do checks, however it doesnt put the element into the current namespace (which possibly may be a logic bug - namespaces internally are so damned confusing). Using the syntax: $node->setAttributeNS("http://www.w3.org/2000/xmlns/";, "xmlns:b", "http://www.somedomain.de/";); This sets the definition on the element but doesnt put that node into the namespace, it just puts the namespace into the scope of the node, so that elements added with createelementns and appended as children of $node can be placed within the namespace and would be prefixed with "b". Now here is the question, if a namespace is not associated on the element at that point, should the above set the element into the new namespace? (Easy enough to implement, but really have no clue if this is the proper logic or not). Any namespace gurus around here? Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: [PHP-XML-DEV] Re: [PHP] PHP5: ext/dom - set namespace of node manually
From: Christian Stocker > > $node->setAttributeNS("http://www.w3.org/2000/xmlns/";, "xmlns:b", > > "http://www.somedomain.de/";); > > > IMHO, that would be very confusing. > > I liked the idea by vivian with a third optional namespaceURI argument > for the element object, so that at least you can use your own extended > classes for that. > > And maybe we still need a ->setNamespaceURI method, even if W3C didnt > think of that ;) After thinking about it some more I started to think about it the same way. One can always then use $node->prefix = "xyz" to set the prefix (if needed) for the initial namespace delcaration. It probably has to wait until 5.1 though since its so close to the release. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: [PHP-XML-DEV] PHP5: ext/dom: Namespace & Prefix unexpected behavior
> I thought that setting $root->prefix will set the prefix and the > namespaceUri to the other domain... but it seems to me that the parser > doesn't see the "xmlns:anotherprefix" as a prefix-declaration? > maybe i just misunderstood something, so please correct me if so. The current behavior is wrong (fix currently being discussed), however your expectations are also incorrect. Setting the prefix does not change a nodes namespace uri. Once a node is created, it is permanently bound to the namespace URI (per specs). Changing the prefix only changes the prefix of the current namespace on that element, which may result in a new namespace definition on that node (if namespace is inherited) or it may fail as in your case there would be namespace collision due to 2 namespaces with the same prefix (which imo should error out rather than allow it). Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: [PHP-XML-DEV] Re: [PHP] PHP5: ext/dom - set namespace of node manually
From: Vivian Steller > i now can use the following syntax to set the namespaceUri of a node: > > $element = new DomElement("tagname", "value", "http://namespaceUri";); > // or > $element = new DomElement("pref:tagname", "value", "http://namespaceUri";); > // works as well > ?> Your point for adding this was well made (as well as others expressing the same view), so support has been added to the DomElement constructor. as well as the examples above, to create a node with no value in a namespace: $element = new DomElement("pref:tagname", NULL, "http://namespaceUri";); Note: There will be no further additional dom features added for 5.0. This was an exception due to its usefulness in functionality. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: REQ: DOMDocument needs a way to format XML code
Daevid Vincent wrote: I have a feature request (and I'm a bit disappointed that this isn't already in the DOMDocument, when there are nearly useless methods like "normalize()")... Ruby has this built in. xmllint has the --format parameter. But yet PHP's DOMDocument has no way of cleaning up the code. Could someone please make a method in PHP v5.x to format the XML. After adding/deleting nodes, the XML gets fairly messy. Ideally it would have an offset character position to start the indent (default of 0 or left margin), and a parameter for how many spaces to use for each indentation (default of say 4 or 5 (same as a tab)). You could just make this optional parameters to saveXML(), but I think it's more flexible to have a DOMDocument->format(offset,spaces); You mean like calling $doc->formatOutput = TRUE; prior to save? Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: CDATA in PHP DOM
Guy Brom wrote: Any idea what's wrong with the following? ($this_item['description'] has some html text I would like to paste as a CDATA section) $item->appendChild($dom->createElement('description', $dom->createCDATASection($this_item['description']))); createElement takes a string not a DOMNode. Append the CDATASection to the element. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: XmlWriter::writeDTD bug...
Jared Williams wrote: Hi, $writer = new XmlWriter(); ... $writer->writeDtd('html', '-//W3C//DTD XHTML 1.0 Strict//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'); produces no whitespace between the public & system ids like... http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";> Has anyone got a workaround for this problem? libxml bug. Add $writer->setIndent(TRUE); before the writeDTD call (can revert it back right after if you dont want indenting). This will force whitespace insertion between the two - not pretty but its a workaround. Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] Re: XmlWriter::writeDTD bug...
Jared Williams wrote: PS. Yeah, thought it was libxml, hence didn't file a pecl bug report. But there does seem a problem with this method as can't just have a publicId or a systemId, libxml function uses NULL as a parameter to specify which id you don't want to use. Which we've lost with the PHP wrapper, as can only specify two strings. Have you tried passing NULL for publicId? :) And systemId can only be NULL if there is no publicId (publicId requires a systemId). Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: XmlReader & XInclude
Only the version of XMLReader in CVS HEAD does at the moment. Rob Jared Williams wrote: Hi, Does PHPs XmlReader support Xinclude ? Seems libxml does reading this post http://mail.gnome.org/archives/xml/2004-February/msg00190.html , but the corresponding constant seems missing in PHP -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
[PHP] Re: Problems getting the nodeName with DomDocument
Kenneth Andresen wrote: I am having problems with the following functions where my return simply is "#text Joe #text Smith #text unknown", it should have read firstname Joe lastname Smith address unknown What am I doing wrong? You're trying to access the name of the Text node which is always #text and not it's parent element. $name = $elem->parentNode->nodeName; Rob -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php