Re: [PHP] SimpleXML and the Single String (SOLVED)
There is another nice way. You can pass a second value to the simple xml constructor which is a class name to be used instead of SimpleXMLElement. You can write your own class that extends SimpleXMLElement and override the magic methods to skip the casting Simon Schick simonsimc...@googlemail.com hat am 22. Februar 2012 um 00:16 geschrieben: Hi, Jay If you're not using the variable *$xmlCompany* somewhere else I'd try to skip the array and just do it with this single line: *$arrayLead[0]-Company = (string) $xml-SignonRq-SignonTransport-CustId-SPName;* The result should not differ from what you have now. Bye Simon 2012/2/21 Jay Blanchard jay.blanch...@sigmaphinothing.org Howdy, My PHP chops are a little rough around the edges so I know that I am missing something. I am working with SimpleXML to retrieve values from an XML file like this - $xmlCompany = $xml-SignonRq-SignonTransport-CustId-SPName; If I echo $xmlCompany I get the proper information. If I use $xmlCompany as an array value though, I get this object - $arrayLead[0]-Company = $xmlCompany; // what I did [Company] = SimpleXMLElement Object // what I got ( [0] = Dadgummit ) I tried casting AND THEN AS I TYPED THIS I figured it out... $xmlCompany = array((string) $xml-SignonRq-SignonTransport-CustId-SPName); // becomes an array $arrayLead[0]-Company = $xmlCompany[0]; // gets the right bit of the array and the result is [Company] = Dadgummit Thanks for bearing with me! Marco Behnke Dipl. Informatiker (FH), SAE Audio Engineer Diploma Zend Certified Engineer PHP 5.3 Tel.: 0174 / 9722336 e-Mail: ma...@behnke.biz Softwaretechnik Behnke Heinrich-Heine-Str. 7D 21218 Seevetal http://www.behnke.biz -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML and the Single String (SOLVED)
On 2/22/2012 8:32 AM, ma...@behnke.biz wrote: There is another nice way. You can pass a second value to the simple xml constructor which is a class name to be used instead of SimpleXMLElement. You can write your own class that extends SimpleXMLElement and override the magic methods to skip the casting I don't really see a need to add an extra layer or class extension when casting works fine. Am I wrong? Why add several lines of code in an extension class? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML and the Single String (SOLVED)
Am 22.02.12 16:04, schrieb Jay Blanchard: On 2/22/2012 8:32 AM, ma...@behnke.biz wrote: There is another nice way. You can pass a second value to the simple xml constructor which is a class name to be used instead of SimpleXMLElement. You can write your own class that extends SimpleXMLElement and override the magic methods to skip the casting I don't really see a need to add an extra layer or class extension when casting works fine. Am I wrong? Why add several lines of code in an extension class? To keep the code readable? $value = $xml-node; vs. $value = (String)$xml-node; I like the first one. Plus you handle it to dynamically to the right type function __get($value) { if is float return float casted value if is boolean ... and so on } -- Marco Behnke Dipl. Informatiker (FH), SAE Audio Engineer Diploma Zend Certified Engineer PHP 5.3 Tel.: 0174 / 9722336 e-Mail: ma...@behnke.biz Softwaretechnik Behnke Heinrich-Heine-Str. 7D 21218 Seevetal http://www.behnke.biz signature.asc Description: OpenPGP digital signature
Re: [PHP] SimpleXML and the Single String (SOLVED)
I don't really see a need to add an extra layer or class extension when casting works fine. Am I wrong? Why add several lines of code in an extension class? To keep the code readable? $value = $xml-node; vs. $value = (String)$xml-node; I like the first one. Plus you handle it to dynamically to the right type function __get($value) { if is float return float casted value if is boolean ... and so on } The code is no less readable my way, YMMV -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML and the Single String (SOLVED)
Hi, Jay If you're not using the variable *$xmlCompany* somewhere else I'd try to skip the array and just do it with this single line: *$arrayLead[0]-Company = (string) $xml-SignonRq-SignonTransport-CustId-SPName;* The result should not differ from what you have now. Bye Simon 2012/2/21 Jay Blanchard jay.blanch...@sigmaphinothing.org Howdy, My PHP chops are a little rough around the edges so I know that I am missing something. I am working with SimpleXML to retrieve values from an XML file like this - $xmlCompany = $xml-SignonRq-SignonTransport-CustId-SPName; If I echo $xmlCompany I get the proper information. If I use $xmlCompany as an array value though, I get this object - $arrayLead[0]-Company = $xmlCompany; // what I did [Company] = SimpleXMLElement Object // what I got ( [0] = Dadgummit ) I tried casting AND THEN AS I TYPED THIS I figured it out... $xmlCompany = array((string) $xml-SignonRq-SignonTransport-CustId-SPName); // becomes an array $arrayLead[0]-Company = $xmlCompany[0]; // gets the right bit of the array and the result is [Company] = Dadgummit Thanks for bearing with me!
Re: [PHP] SimpleXML/array duality (like particles waves)
On Tue, Sep 28, 2010 at 4:29 PM, Brian Dunning br...@briandunning.comwrote: I am kind of jacked here. I have a SimpleXML object that's been converted to an array. how was the SimpleXMLElement converted to an array? -nathan
Re: [PHP] SimpleXML/array duality (like particles waves)
If you read down to the bottom of the post, the function I used is given. On Sep 28, 2010, at 3:47 PM, Nathan Nobbe wrote: On Tue, Sep 28, 2010 at 4:29 PM, Brian Dunning br...@briandunning.com wrote: I am kind of jacked here. I have a SimpleXML object that's been converted to an array. how was the SimpleXMLElement converted to an array? -nathan
Re: [PHP] SimpleXML/array duality (like particles waves)
On Tue, Sep 28, 2010 at 5:06 PM, Brian Dunning br...@briandunning.comwrote: If you read down to the bottom of the post, the function I used is given. My apologies for the hasty response. well, if i had to guess, id say thats where the problem is. why cant you just iterate over the object w/ the built in functionality, which is to say, why bother converting to an array in the first place? -nathan
Re: [PHP] simplexml choking on apparently valid XML - Solved
I was able to resolve this by changing the XML file encoding from UTF-8 to ISO-8859-1. Works like a charm now, with the XML-encoded characters. Thanks to all who offered their help. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml choking on apparently valid XML
I think that should be amp; because you cant use in xml as independent alphbet On 5/7/10, Dan Joseph dmjos...@gmail.com wrote: On Thu, May 6, 2010 at 8:02 PM, Brian Dunning br...@briandunning.comwrote: Hey all - I'm using simplexml-load-string just to validation a string of XML, and libxml-get-errors to return any errors. It's always worked before, but today it's choking on this line in the XML: client_orderitem_numberBasketball Personalized Notebook - Jeffapos;s/client_orderitem_number It's returning Premature end of data in tag client_orderitem_number line 90 but as far as I can tell, Jeffapos;s is properly XML encoded. I can't debug this. Any suggestions? I have run the XML through a couple of online validators and it does come back as valid with no errors found. http://www.php.net/unsub.php I had this problem It turned out to be some special characters in the tags or data that I had to strip out first, then load it thru the simplexml parser. I will have to check my code when I get back to the office in the AM and I'll let you know what it was if you haven't figured it out by then. But that might get you started in fixing it. -- -Dan Joseph www.canishosting.com - Unlimited Hosting Plans start @ $3.95/month. Promo Code NEWTHINGS for 10% off initial order http://www.facebook.com/canishosting http://www.facebook.com/originalpoetry -- Sent from my mobile device Devendra Jadhav देवेंद्र जाधव -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml choking on apparently valid XML
- amp; added space because browser is converting it to :) On 5/8/10, Deva devendra...@gmail.com wrote: I think that should be amp; because you cant use in xml as independent alphbet On 5/7/10, Dan Joseph dmjos...@gmail.com wrote: On Thu, May 6, 2010 at 8:02 PM, Brian Dunning br...@briandunning.comwrote: Hey all - I'm using simplexml-load-string just to validation a string of XML, and libxml-get-errors to return any errors. It's always worked before, but today it's choking on this line in the XML: client_orderitem_numberBasketball Personalized Notebook - Jeffapos;s/client_orderitem_number It's returning Premature end of data in tag client_orderitem_number line 90 but as far as I can tell, Jeffapos;s is properly XML encoded. I can't debug this. Any suggestions? I have run the XML through a couple of online validators and it does come back as valid with no errors found. http://www.php.net/unsub.php I had this problem It turned out to be some special characters in the tags or data that I had to strip out first, then load it thru the simplexml parser. I will have to check my code when I get back to the office in the AM and I'll let you know what it was if you haven't figured it out by then. But that might get you started in fixing it. -- -Dan Joseph www.canishosting.com - Unlimited Hosting Plans start @ $3.95/month. Promo Code NEWTHINGS for 10% off initial order http://www.facebook.com/canishosting http://www.facebook.com/originalpoetry -- Sent from my mobile device Devendra Jadhav देवेंद्र जाधव -- Sent from my mobile device Devendra Jadhav देवेंद्र जाधव -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml choking on apparently valid XML
On 8 May 2010 00:39, Nathan Nobbe quickshif...@gmail.com wrote: hmm, both the strings seem to work fine on my laptop: +1. Have no problem with either string -- hype WWW: http://plphp.dk / http://plind.dk LinkedIn: http://www.linkedin.com/in/plind Flickr: http://www.flickr.com/photos/fake51 BeWelcome: Fake51 Couchsurfing: Fake51 /hype -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml choking on apparently valid XML
This time simplexml-load-string also gave me the same error on the following line: first_nameCharlie amp; Brady/first_name Can anyone confirm whether simplexml-load-string will or will not accept or allow XML-encoded characters? It seems that it should and would be pretty surprising if it wouldn't. On May 6, 2010, at 5:02 PM, Brian Dunning wrote: Hey all - I'm using simplexml-load-string just to validation a string of XML, and libxml-get-errors to return any errors. It's always worked before, but today it's choking on this line in the XML: client_orderitem_numberBasketball Personalized Notebook - Jeffapos;s/client_orderitem_number It's returning Premature end of data in tag client_orderitem_number line 90 but as far as I can tell, Jeffapos;s is properly XML encoded. I can't debug this. Any suggestions? I have run the XML through a couple of online validators and it does come back as valid with no errors found. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml choking on apparently valid XML
On Fri, May 7, 2010 at 4:32 PM, Brian Dunning br...@briandunning.comwrote: This time simplexml-load-string also gave me the same error on the following line: first_nameCharlie amp; Brady/first_name Can anyone confirm whether simplexml-load-string will or will not accept or allow XML-encoded characters? It seems that it should and would be pretty surprising if it wouldn't. hmm, both the strings seem to work fine on my laptop: php var_dump(simplexml_load_string('first_nameCharlie amp; Brady/first_name')); object(SimpleXMLElement)#1 (1) { [0]= string(15) Charlie Brady } php var_dump(simplexml_load_string('client_orderitem_numberBasketball Personalized Notebook - Jeffapos;s/client_orderitem_number')); object(SimpleXMLElement)#1 (1) { [0]= string(41) Basketball Personalized Notebook - Jeff's } -nathan
Re: [PHP] simplexml choking on apparently valid XML
On Thu, May 6, 2010 at 8:02 PM, Brian Dunning br...@briandunning.comwrote: Hey all - I'm using simplexml-load-string just to validation a string of XML, and libxml-get-errors to return any errors. It's always worked before, but today it's choking on this line in the XML: client_orderitem_numberBasketball Personalized Notebook - Jeffapos;s/client_orderitem_number It's returning Premature end of data in tag client_orderitem_number line 90 but as far as I can tell, Jeffapos;s is properly XML encoded. I can't debug this. Any suggestions? I have run the XML through a couple of online validators and it does come back as valid with no errors found. http://www.php.net/unsub.php I had this problem It turned out to be some special characters in the tags or data that I had to strip out first, then load it thru the simplexml parser. I will have to check my code when I get back to the office in the AM and I'll let you know what it was if you haven't figured it out by then. But that might get you started in fixing it. -- -Dan Joseph www.canishosting.com - Unlimited Hosting Plans start @ $3.95/month. Promo Code NEWTHINGS for 10% off initial order http://www.facebook.com/canishosting http://www.facebook.com/originalpoetry
Re: [PHP] SimpleXML: convert xml to text
On Sun, 2010-03-14 at 21:58 +0800, Dasn wrote: Hello, I want to convert some xml stuff to simple string using php, say: ?php $string = XML a left foocenter1okok/okcenter2/fooright /a XML; $xml = simplexml_load_string($string); echo $xml; ? The code will output left right while all the central stuff was lost. How should I print it as left center1 ok center2 right ? Thanks in advance, and please Cc me. :) -- Dasn Can't you just call strip_tags() on the string? As you don't need to echo any attribute values, I would have thought it would be perfect. As XML is meant to be well-formed anyway, strip_tags shouldn't cause any problems with broken or missing closing tags. Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] SimpleXML: convert xml to text
On Sun, 14 Mar 2010 22:02:22 +0800, Ashley Sheridan wrote: On Sun, 2010-03-14 at 21:58 +0800, Dasn wrote: Hello, I want to convert some xml stuff to simple string using php, say: ?php $string = XML a left foocenter1okok/okcenter2/fooright /a XML; $xml = simplexml_load_string($string); echo $xml; ? The code will output left right while all the central stuff was lost. How should I print it as left center1 ok center2 right ? Thanks in advance, and please Cc me. :) Can't you just call strip_tags() on the string? As you don't need to echo any attribute values, I would have thought it would be perfect. As XML is meant to be well-formed anyway, strip_tags shouldn't cause any problems with broken or missing closing tags. Thanks Ashley for your reply. Sorry that my description was not clear enough. Actually I don't want to just strip the tags, sometimes I also wanna change some elements. For another example: ablafunctionstrip_tags/functionbla/a. When output, I also want to make some change to the data depending on the tags, say, trying to append a pair of () to the function element, printing it as bla strip_tags() bla. The problem is when I processing the nodes with SimpleXML, I couldn't get the right order of the data. That is : echo $xml-a, (string) $xml-a-function . '()' // prints bla bla strip_tags() Thank you anyway. Cc please. -- Dasn -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML: convert xml to text
On Sun, 14 Mar 2010 22:02:22 +0800, Ashley Sheridan wrote: On Sun, 2010-03-14 at 21:58 +0800, Dasn wrote: Hello, I want to convert some xml stuff to simple string using php, say: ?php $string = XML a left foocenter1okok/okcenter2/fooright /a XML; $xml = simplexml_load_string($string); echo $xml; ? The code will output left right while all the central stuff was lost. How should I print it as left center1 ok center2 right ? Thanks in advance, and please Cc me. :) Well I change to use xmlparser instead, never mind. :) -- Dasn -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml - can it do what I need?
On Sun, 2010-02-07 at 23:24 -0800, TerryA wrote: Hi Carlos I looked at the documentation for hours but don't see any solution. I'm uploading a sample file here. The full file contains around 100 properties but the uploaded file has just one. I need to extract data from this file to write to a MySQL database. I have no problem in doing this until it comes to the elements-element tags. I only need 3 of these elements. I can extract the data by iteration but that does not help me to get the three specific element tags that I need because there are some tags that appear for some properties and not for others so the order is different. Here is the file: http://old.nabble.com/file/p27496211/annnonces.xml annnonces.xml Thanks Terry -- View this message in context: http://old.nabble.com/simplexml---can-it-do-what-I-need--tp27481222p27496211.html Sent from the PHP - General mailing list archive at Nabble.com. As you iterate the elements tags, check their attributes with getAttribute(). Thanks, Ash http://www.ashleysheridan.co.uk
Re: [PHP] simplexml - can it do what I need?
Hi Guys Thanks for all your input. This forum is great! I can get the attributes OK but I can't code the checking routing correctly. This is what I have: Many thanks again for your input. I tried this but it only gives me the data for each element. I need to be able to access the attributes of the data in order to select only those elements that I need. This is the code that I have at present: ?php $file= 'annnonces.xml'; // load file $xml = simplexml_load_file($file) or die (Unable to load XML file!); foreach ($xml-xpath('//lot') as $lot) { echo $lot-numero_lot, 'type ', $lot-type, $lot-identification, 'br /'; echo 'Prix maxi: ', $lot-tarif_max, ' Prix mini: ', $lot-tarif_min, 'br /'; foreach( $lot-elements-element as $key = $data ){ $result=((string) $data-attributes()); if ($result='17') { echo $data; } } } ? But this just gives the data for every element. Any ideas on how to get just the data for the element when the attribute is 17? Terry -- View this message in context: http://old.nabble.com/simplexml---can-it-do-what-I-need--tp27481222p27496987.html Sent from the PHP - General mailing list archive at Nabble.com. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml - can it do what I need?
Got it! I corrected my syntax and this code now works as far as I can tell: ?php $file= 'annnonces.xml'; // load file $xml = simplexml_load_file($file) or die (Unable to load XML file!); foreach ($xml-xpath('//lot') as $lot) { echo $lot-numero_lot, 'type ', $lot-type, $lot-identification, 'br /'; echo 'Prix maxi: ', $lot-tarif_max, ' Prix mini: ', $lot-tarif_min, 'br /'; foreach( $lot-elements-element as $key = $data ){ $result=((string) $data-attributes()); if ($result == 1) { echo Nombre pièces: , $data, 'br /'; } if ($result == 3) { echo Surface: , $data, m2, 'br /'; } if ($result == 7) { echo Nombre étoiles: , $data, 'br /'; break; } } } ? Output is: 201type APPARTEMENT STUDIOTEE2 106 Prix maxi: 475 Prix mini: 475 Nombre pièces: 1 Surface: 27m2 Nombre étoiles: 3 Hooray and thanks to all of you guys. Terry -- View this message in context: http://old.nabble.com/simplexml---can-it-do-what-I-need--tp27481222p27500759.html Sent from the PHP - General mailing list archive at Nabble.com. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml - can it do what I need?
Hi Shawn Thanks for answering my query. I have looked at the suggestions: $xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOCDATA); I am/was able to load the file OK and to access the data by iteration. However, I can't find a way to extract data by attributes. I need something like $string=element idtype=11 lang=fr label=Description - Etage. Obviously, that won't work but that's the result I need. How do I get the data out of one of these elements by specifying its idtype and lang? I've google for hours on this and for another hour on SimpleXMLElement. Terry -- View this message in context: http://old.nabble.com/simplexml---can-it-do-what-I-need--tp27481222p27486649.html Sent from the PHP - General mailing list archive at Nabble.com. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml - can it do what I need?
TerryA schrieb: Hi Shawn Thanks for answering my query. I have looked at the suggestions: $xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOCDATA); I am/was able to load the file OK and to access the data by iteration. However, I can't find a way to extract data by attributes. I need something like $string=element idtype=11 lang=fr label=Description - Etage. Obviously, that won't work but that's the result I need. How do I get the data out of one of these elements by specifying its idtype and lang? I've google for hours on this and for another hour on SimpleXMLElement. Terry Hi Terry, look at the PHP.NET documentation. There indicates the use of simpleXMLElement structures. If you want to extract elements from this object, please read there how this work. By the way, it would be interesting to see, how your XML is made. May be is usefull to use another class like DOM. regards carlos http://de2.php.net/manual/fr/book.simplexml.php http://de2.php.net/manual/fr/refs.xml.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml - can it do what I need?
Hi Carlos I looked at the documentation for hours but don't see any solution. I'm uploading a sample file here. The full file contains around 100 properties but the uploaded file has just one. I need to extract data from this file to write to a MySQL database. I have no problem in doing this until it comes to the elements-element tags. I only need 3 of these elements. I can extract the data by iteration but that does not help me to get the three specific element tags that I need because there are some tags that appear for some properties and not for others so the order is different. Here is the file: http://old.nabble.com/file/p27496211/annnonces.xml annnonces.xml Thanks Terry -- View this message in context: http://old.nabble.com/simplexml---can-it-do-what-I-need--tp27481222p27496211.html Sent from the PHP - General mailing list archive at Nabble.com. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml - can it do what I need?
TerryA wrote: My first post and I'm just a few days into learning PHP so that I can extract data from an XML feed for updating a MySQL driven website. Simplexml grabs most of my data without a problem but I can't get at the data in elements such as: element idtype=11 lang=fr label=Description - Etage![CDATA[Rez de jardin]]/element element idtype=1 lang=fr label=Description - Nombre de pièces![CDATA[1]]/element element idtype=2 lang=fr label=Description - Nombre de chambres![CDATA[0]]/element element idtype=3 lang=fr label=Description - Surface totale (m²)![CDATA[27]]/element I have around a hundred of these elements but only need data from two of them. I need to extract the CDATA by specifying the idtype and lang attribute. For example, in the first of these elements, I need to be able to get out the string Rez de jardin by specifying idtype=11 and lang=fr. Can I use Simplexml to do this and, if so, how? If not, what should I use? Many thanks for any help. Terry Look at the options: $xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOCDATA); -- Thanks! -Shawn http://www.spidean.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML output encoding
At 2:40 PM +0200 5/5/09, Ondrej Kulaty wrote: Hi, is there any way how to set output encoding for SimpleXML? It will load XML document in any encoding, but internally, it converts the document to UTF-8 and outputs it in this encoding. I would like to have output encoding set to ISO-8859-2, is it possible? thanks. -- Ondrej Kulaty Why? http://www.cl.cam.ac.uk/~mgk25/unicode.html tedd -- --- http://sperling.com http://ancientstones.com http://earthstones.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML output encoding
Because i am working on an old system which is in ISO, i cant use unicode. -- Ondrej Kulaty tedd tedd.sperl...@gmail.com píse v diskusním príspevku news:p06240802c625f6b4e...@[192.168.1.101]... At 2:40 PM +0200 5/5/09, Ondrej Kulaty wrote: Hi, is there any way how to set output encoding for SimpleXML? It will load XML document in any encoding, but internally, it converts the document to UTF-8 and outputs it in this encoding. I would like to have output encoding set to ISO-8859-2, is it possible? thanks. -- Ondrej Kulaty Why? http://www.cl.cam.ac.uk/~mgk25/unicode.html tedd -- --- http://sperling.com http://ancientstones.com http://earthstones.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML - issue with getting data out of the object returned
Tim-Hinnerk Heuer http://www.ihostnz.com On Fri, Dec 19, 2008 at 3:50 PM, Dan Joseph dmjos...@gmail.com wrote: Hi, I have a basic XML document that I am grabbing with simplexml_load_string(), here is the print_r: SimpleXMLElement Object ( [Package] = SimpleXMLElement Object ( [PackageID] = 804 [PackageName] = Silver [BandwidthGB] = 20 [WebStorageMB] = 5120 [DBStorageMB] = 250 [POPMailBoxes] = 50 [WebStorageUnits] = 5 [BandwidthUnits] = 1 [DBStorageUnits] = 1 [POPUnits] = 5 [DomainHeaders] = 50 [DBType] = MSSQL [OSType] = Windows [Enabled] = True ) [Count] = 1 ) When I try and access $x-Package-PackageID I don't get 804, I get: SimpleXMLElement Object ( [0] = 804 ) Had that problem before: $val = (string) $x-Package-PackageID; or $val = (int) $x-Package-PackageID; or whatever type you want. ;) Could someone tell me how I just get the value 804 out of there? -- -Dan Joseph www.canishosting.com - Plans start @ $1.99/month. Build a man a fire, and he will be warm for the rest of the day. Light a man on fire, and will be warm for the rest of his life.
Re: [PHP] SimpleXML - issue with getting data out of the object returned
On Thu, Dec 18, 2008 at 10:01 PM, German Geek geek...@gmail.com wrote: $val = (string) $x-Package-PackageID; or $val = (int) $x-Package-PackageID; Ha... I would have never figured that out... Thank you to you both! That did the trick. -- -Dan Joseph www.canishosting.com - Plans start @ $1.99/month. Build a man a fire, and he will be warm for the rest of the day. Light a man on fire, and will be warm for the rest of his life.
Re: [PHP] SimpleXML strange behaviour.
2008/9/9 Mirco Soderi [EMAIL PROTECTED] Do you know any reason why the following code does work $xmlOperazioni = simplexml_load_file($xmlFilename); foreach($xmlOperazioni-operazione as $operazione) { if($operazione['nome'] == $operazioneRichiesta) { require($operazione['php']); break; } } but the following does not $xmlOperazioni = simplexml_load_file($impostazioni['root']['configurazione']['generale']['xml_operazioni']); foreach($xmlOperazioni-operazione as $operazione) { if($operazione-nome == $operazioneRichiesta) { require($operazione-php); break; } } well im guessing thats because youre using the same file and different accessors, what i mean is that if $xmlFilename, and $impostazioni['root']['configurazione']['generale']['xml_operazioni'] refer to the same xml from above, then obviously this wont work.. this is looking for an attribute, 'nome', $operazione['nome']; this is looking for a child element, 'nome', $operazione-nome that is I MUST access childrens of the element operazione as if it was an array, while (in the same page) the following code does work $xmlViste = simplexml_load_file($impostazioni['root']['configurazione']['generale']['xml_composizione_viste']); foreach($xmlViste-vista as $vista) { if($vista-nome == $nomeVistaDaMostrare) { $smarty-assign(intestazione,componenti/.$vista-intestazione); $smarty-assign(menu,componenti/.$vista-menu); $smarty-assign(contenuto, componenti/.$vista-contenuto); $smarty-assign(pie_di_pagina, componenti/.$vista-pie_di_pagina); break; } } but the following does not $xmlViste = simplexml_load_file($impostazioni['root']['configurazione']['generale']['xml_composizione_viste']); foreach($xmlViste-vista as $vista) { if($vista['nome'] == $nomeVistaDaMostrare) { $smarty-assign(intestazione,componenti/.$vista['intestazione']); $smarty-assign(menu,componenti/.$vista['menu']); $smarty-assign(contenuto, componenti/.$vista['contenuto']); $smarty-assign(pie_di_pagina, componenti/.$vista['pie_di_pagina']); break; } } again, this syntax denotes a child element, $vista-nome this syntax denotes an attribute $vista['nome'] that is this time I MUST access the childrens of the element operazione as if it was an object? i recommend a review of the example page on simple xml, but yes children are access via the - notation, you can also use the children() method if its more convenient for you. http://us2.php.net/manual/en/simplexml.examples.php -nathan
Re: [PHP] simplexml
You have to handle the html special chars. == amp; On Thu, Jul 10, 2008 at 10:59 AM, Joakim Ling [EMAIL PROTECTED] wrote: Hi I'm using simplexml to create some xml files. Here's a stripped example, how can I get this to work? Tried millions different ways still no joy. ?php header(Content-type: text/xml); $xml = simplexml_load_string('root/root'); $root = $xml-addChild('tests'); $root-addChild('test', 'test test'); echo $xml-asXML(); ? // cheers jo
Re: [PHP] simplexml
You have to handle the html special chars. == amp; On Thu, Jul 10, 2008 at 10:59 AM, Joakim Ling [EMAIL PROTECTED] wrote: Hi I'm using simplexml to create some xml files. Here's a stripped example, how can I get this to work? Tried millions different ways still no joy. ?php header(Content-type: text/xml); $xml = simplexml_load_string('root/root'); $root = $xml-addChild('tests'); $root-addChild('test', 'test test'); echo $xml-asXML(); ? // cheers jo
Re: [PHP] simplexml
On Thu, Jul 10, 2008 at 10:55 AM, Nate Tallman [EMAIL PROTECTED] wrote: You have to handle the html special chars. == amp; and if you use the SimpleXMLElement constructor, it will throw an exception, rather than just return false, which is useful, because it tells you what went wrong. -nathan
Re: [PHP] SimpleXML addChild() namespace problem
On Jan 18, 2008 12:04 PM, Carole E. Mah [EMAIL PROTECTED] wrote: I did exactly this, and still got: ?xml version=1.0 encoding=UTF-8? rss xmlns:itunes=http://www.itunes.com/dtds/podcast-1.0.dtd; version= 2.0 channel !-- snipping, some elements omitted ... -- item titleMy Title/title linkMy Link/link descriptionMy Description/description itunes:author xmlns:itunes=itunesMy Author/itunes:author itunes:subtitle xmlns:itunes=itunesMy Subtitle/itunes:subtitle !-- snipping, more elements omitted ... -- /item /channel /rss are you trying to read an existing document into a SimpleXMLElement, or are you trying to create a SimpleXMLElement instance and generate a document from that? my impression was you were trying to do the later; please clarify and if you are trying to do the later, post the code you are using to create the SimpleXMLElement instance and generate the output youve posted. -nathan
Re: [PHP] SimpleXML addChild() namespace problem
On Jan 18, 2008 12:22 PM, Nathan Nobbe [EMAIL PROTECTED] wrote: Are you trying to read an existing document into a SimpleXMLElement, or are you trying to create a SimpleXMLElement instance and generate a document from that? My impression was you were trying to do the later; please clarify and if you are trying to do the later, post the code you are using to create the SimpleXMLElement instance and generate the output youve posted. Nathan, I am trying to to the latter -- create a SimpleXMLElement instance and generate a document from that. Thank you very much for all your examples and patience. I now see the very silly mistake I made. Correct (from your example): $xml = new SimpleXMLElement('root xmlns:itunes=http://apple.com/'); $n = $xml-addChild(subtitle, Musical Mockery, http://apple.com;); Incorrect (what I was doing): $xml = new SimpleXMLElement('root xmlns:itunes=http://apple.com/'); $n = $xml-addChild(subtitle, Musical Mockery, itunes); To be fair, there really isn't an example of this on PHP.net. Nonetheless, I feel a bit foolish for having wasted your time with this. Thank you for your help. Carole -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML addChild() namespace problem
based upon information from bug #43221, if you define the namespace beforehand it will work. ?php $xml = new SimpleXMLElement('root xmlns:itunes=http://apple.com/'); $n = $xml-addChild(subtitle, Musical Mockery, http://apple.com;); print_r($xml-asXml()); ? produces: ?xml version=1.0? root xmlns:itunes=http://apple.com;itunes:subtitleMusical Mockery/itunes:subtitle/root -nathan Actually, it doesn't work. I did exactly this, and still got: ?xml version=1.0 encoding=UTF-8? rss xmlns:itunes=http://www.itunes.com/dtds/podcast-1.0.dtd; version=2.0 channel !-- snipping, some elements omitted ... -- item titleMy Title/title linkMy Link/link descriptionMy Description/description itunes:author xmlns:itunes=itunesMy Author/itunes:author itunes:subtitle xmlns:itunes=itunesMy Subtitle/itunes:subtitle !-- snipping, more elements omitted ... -- /item /channel /rss -Carole -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML addChild() namespace problem
On Jan 18, 2008 2:48 PM, Carole E. Mah [EMAIL PROTECTED] wrote: On Jan 18, 2008 12:22 PM, Nathan Nobbe [EMAIL PROTECTED] wrote: Are you trying to read an existing document into a SimpleXMLElement, or are you trying to create a SimpleXMLElement instance and generate a document from that? My impression was you were trying to do the later; please clarify and if you are trying to do the later, post the code you are using to create the SimpleXMLElement instance and generate the output youve posted. Nathan, I am trying to to the latter -- create a SimpleXMLElement instance and generate a document from that. Thank you very much for all your examples and patience. I now see the very silly mistake I made. Correct (from your example): $xml = new SimpleXMLElement('root xmlns:itunes=http://apple.com/'); $n = $xml-addChild(subtitle, Musical Mockery, http://apple.com;); Incorrect (what I was doing): $xml = new SimpleXMLElement('root xmlns:itunes=http://apple.com/'); $n = $xml-addChild(subtitle, Musical Mockery, itunes); To be fair, there really isn't an example of this on PHP.net. Nonetheless, I feel a bit foolish for having wasted your time with this. Thank you for your help. no prob; i learned how to do this on this post myself ;) glad to hear its working now! -nathan
Re: [PHP] SimpleXML addChild() namespace problem
On Jan 14, 2008 11:21 PM, Carole E. Mah [EMAIL PROTECTED] wrote: Yes, I tried the following: http://us3.php.net/manual/en/function.dom-domdocument-createelementns.php Same results. based upon information from bug #43221, if you define the namespace beforehand it will work. ?php $xml = new SimpleXMLElement('root xmlns:itunes=http://apple.com/'); $n = $xml-addChild(subtitle, Musical Mockery, http://apple.com;); print_r($xml-asXml()); ? produces: ?xml version=1.0? root xmlns:itunes=http://apple.com;itunes:subtitleMusical Mockery/itunes:subtitle/root -nathan
Re: [PHP] SimpleXML Bug question
On Tue, January 15, 2008 12:34 am, Naz Gassiep wrote: What's the current status on this bug: http://bugs.php.net/bug.php?id=39164 Regardless of what the PHP developers say in those comments, the modification of data when it is read is not correct. If it is intended behavior, then the developer/s who intend it to be that way are wrong. Under no circumstances can it be considered appropriate for any read operation to write anything. Some clarity on this matter would be great. The current status is closed as bogus. I dunno WHY they think it's bogus, but there it is. Perhaps if you emailed Helly and asked what his thinking was, and asked politely on php-internals for anybody to comment on why it should be that way, you'd get a better response. I don't use XML nor simpleXML enough to really comment, but at first glance, I'd have to say that the auto-creation of a node is pretty wrong. More research might make me change my mind... Suppose, for example, that the XML spec REQUIRES at least one valid node, and your XML is malformed without it. If that were the case, PHP forcing it to be valid by adding a dummy node seems perfectly reasonable. You may want to also consider submitting a patch if you really think it's wrong, and you've managed to find the commit that causes the problem. -- Some people have a gift link here. Know what I want? I want you to buy a CD from some indie artist. http://cdbaby.com/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML addChild() namespace problem
On Jan 14, 2008 10:22 PM, Carole E. Mah [EMAIL PROTECTED] wrote: This is problematic code, even though it works, because it auto-generates an unnecessary xmlns: attribute: $item-addChild('itunes:subtitle', $mySubTitle,itunes); It generates the following XML: itunes:subtitle xmlns:itunes=itunesMusical Mockery/itunes:subtitle When really all we want is this: itunes:subtitleMusical Mockery/itunes:subtitle Furthermore, dumping it into a DomDocument and attempting to use removeAttributeNS() to remove the spurious attribute removes the entire kit and kaboodle, leaving only: subtitleMusical Mockery/subtitle How can one get the desired result, short of using a regexp? (I have done this, and it works, but is a silly hack because it doesn't use XML parsing to address an XML problem). have you considered appending the child w/ w/e the DOM extension has, just to see if the namespace specification is unintentionally added by it as well? -nathan
Re: [PHP] SimpleXML addChild() namespace problem
Yes, I tried the following: http://us3.php.net/manual/en/function.dom-domdocument-createelementns.php Same results. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml problem
On Dec 31, 2007 7:11 AM, Dani Castaños [EMAIL PROTECTED] wrote: Hi all! I'm using simplexml to load an xml into an object. The XML is this: ?xml version=1.0? request customerID3/customerID appNameagenda/appName ticketTypecticket_agenda_server/ticketType ticketTypeID1/ticketTypeID platformID1/platformID ticketActionaddUsersToGroup/ticketAction /request When I do this: $file = simplexml_load_file( 'file.xml' ); $ticketType = $file-ticketType; What i really have into $ticketType is a SimpleXMLElement... not the value cticket_agenda_server... What am I doing wrong? cast the value to a string when you pull it out if you want to use it that way: ?php $xml = XML ?xml version=1.0? request customerID3/customerID appNameagenda/appName ticketTypecticket_agenda_server/ticketType ticketTypeID1/ticketTypeID platformID1/platformID ticketActionaddUsersToGroup/ticketAction /request XML; $file = new SimpleXMLElement($xml); $ticketTypeAsSimpleXmlElement = $file-ticketType; $ticketTypeAsString = (string)$file-ticketType; $ticketTypeAnalyzer = new ReflectionObject($ticketTypeAsSimpleXmlElement); echo (string)$ticketTypeAnalyzer . PHP_EOL; var_dump($ticketTypeAsString); ? -nathan
Re: [PHP] simplexml problem
Nathan Nobbe escribió: On Dec 31, 2007 7:11 AM, Dani Castaños [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: Hi all! I'm using simplexml to load an xml into an object. The XML is this: ?xml version=1.0? request customerID3/customerID appNameagenda/appName ticketTypecticket_agenda_server/ticketType ticketTypeID1/ticketTypeID platformID1/platformID ticketActionaddUsersToGroup/ticketAction /request When I do this: $file = simplexml_load_file( 'file.xml' ); $ticketType = $file-ticketType; What i really have into $ticketType is a SimpleXMLElement... not the value cticket_agenda_server... What am I doing wrong? cast the value to a string when you pull it out if you want to use it that way: ?php $xml = XML ?xml version=1.0? request customerID3/customerID appNameagenda/appName ticketTypecticket_agenda_server/ticketType ticketTypeID1/ticketTypeID platformID1/platformID ticketActionaddUsersToGroup/ticketAction /request XML; $file = new SimpleXMLElement($xml); $ticketTypeAsSimpleXmlElement = $file-ticketType; $ticketTypeAsString = (string)$file-ticketType; $ticketTypeAnalyzer = new ReflectionObject($ticketTypeAsSimpleXmlElement); echo (string)$ticketTypeAnalyzer . PHP_EOL; var_dump($ticketTypeAsString); ? -nathan Thanks! Problem fixed... But I think PHP must do the cast automatically. I think it's a bug fixed in a further version than mine as I've read -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml problem
On Dec 31, 2007 10:09 AM, Dani Castaños [EMAIL PROTECTED] wrote: Thanks! Problem fixed... But I think PHP must do the cast automatically. I think it's a bug fixed in a further version than mine as I've read no problem; but just fyi, its not a bug; the behavior is as expected per the manual: http://us3.php.net/manual/en/ref.simplexml.php *Example#6 Comparing Elements and Attributes with Text* To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using *(string)*. Otherwise, PHP treats the element as an object. if you use an operation that casts implicitly, such as echo, you dont have to cast yourself; otherwise you do :) -nathan
Re: [PHP] SimpleXML error
I'm not sure, but try casting $xml-title to string, like this: $title = (string) $xml-title; On Nov 26, 2007, at 1:44 PM, Skip Evans [EMAIL PROTECTED] wrote: Hey all, I have some XML files I need to parse and then display (they have HTML formatting in them as well). They contain the following: ?xml version=1.0 ? !DOCTYPE html PUBLIC -//Gale//DTD Gale eBook Document DTD 20031113//EN galeeBkdoc.dtd html gale:versionNumber=OEB 1.2, Gale 1.3 head gale:docName gale:zzNumber=2536600565/ gale:documentCitation gale:pageRange214-215/gale:pageRange /gale:documentCitation titleThomas Jefferson and the Revision of the Virginia Laws/title /head I am then attempting to extract the title with this: $xml = simplexml_load_file(BASE_DIR.'/content/'.$r['filename']); $title= $xml-title; But in the browser I get the following warning. namespace error : Namespace prefix gale for versionNumber on html is not defined... Is this because it is not locating the file galeeBkdoc.dtd, which defines all the elements in the XML files? It is located in the same directory as the content. I have also tried putting the complete path via HTTP in with the name of the DTD file with no luck. Suggestions would be greatly appreciated. Thanks! Skip -- Skip Evans Big Sky Penguin, LLC 503 S Baldwin St, #1 Madison, WI 53703 608-250-2720 http://bigskypenguin.com =-=-=-=-=-=-=-=-=-= Check out PHPenguin, a lightweight and versatile PHP/MySQL, AJAX DHTML development framework. http://phpenguin.bigskypenguin.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML end of element/tag error
the code section is displayed below $xml = simplexml_load_file($_POST['feedurl']); foreach($xml-TT as $TT) { foreach($TT-TOTS as $TOTS) { $cnt++; foreach($TT-TOTS[$cnt]-attributes() as $a = $b) // problematic line. { // DISPLAY THE TITLE AND THE VALUES //echo $a $b br/; } } } the error occours when the parser reaches the end of the last element and then fires the error Fatal error: Call to a member function attributes() on a non-object in line (see problematic line) How can i solve that or determine when there are no more tags to parse. JM Guillermin [EMAIL PROTECTED] wrote: And with : foreach ($xml as $cs) { . } ?? jm - Original Message - From: Don Don To: PHP List Sent: Thursday, April 05, 2007 10:32 AM Subject: [PHP] SimpleXML end of element/tag error I am using simple xml to parse an xml file, the program parses the file and produces an error at the end of the foreach loop when it reaches the end of the tag, it tries to look for an element/tag when there is none and produces an error Call to a member function attributes() on a non-object the foreach loop looks like this foreach($xml-CS as $CS) { //processing takes place here } when there are no more CS it fires an error How can i detect when there are no more elements/tags to parse and handle it? cheers - It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. - Now that's room service! Choose from over 150,000 hotels in 45,000 destinations on Yahoo! Travel to find your fit.
Re: [PHP] SimpleXML end of element/tag error
And with : foreach ($xml as $cs) { . } ?? jm - Original Message - From: Don Don [EMAIL PROTECTED] To: PHP List php-general@lists.php.net Sent: Thursday, April 05, 2007 10:32 AM Subject: [PHP] SimpleXML end of element/tag error I am using simple xml to parse an xml file, the program parses the file and produces an error at the end of the foreach loop when it reaches the end of the tag, it tries to look for an element/tag when there is none and produces an error Call to a member function attributes() on a non-object the foreach loop looks like this foreach($xml-CS as $CS) { //processing takes place here } when there are no more CS it fires an error How can i detect when there are no more elements/tags to parse and handle it? cheers - It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml and serialize error
On Sat, April 29, 2006 8:30 pm, Anthony Ettinger wrote: Warning: var_dump() [function.var-dump]: Node no longer exists in Foo.php on line 78 object(SimpleXMLElement)#86 (0) { } [title]= I turn an xml string into a simplexml object, and then ran serialize() on it before caching the output locally. When I read it back in and run unserialize() to do a dump, I get this error. WILD GUESS!!! Whatever class objects you had defined before you serialized the data, are not defined when you unserialize the data. You need to load all your class files in both serialize and unserialize scripts -- The class definition is not stored in serialized data, just the class 'data' -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simplexml and serialize error
Richard Lynch wrote: On Sat, April 29, 2006 8:30 pm, Anthony Ettinger wrote: Warning: var_dump() [function.var-dump]: Node no longer exists in Foo.php on line 78 object(SimpleXMLElement)#86 (0) { } [title]= I turn an xml string into a simplexml object, and then ran serialize() on it before caching the output locally. When I read it back in and run unserialize() to do a dump, I get this error. WILD GUESS!!! Whatever class objects you had defined before you serialized the data, are not defined when you unserialize the data. You need to load all your class files in both serialize and unserialize scripts -- The class definition is not stored in serialized data, just the class 'data' A DIFFERENT WILD GUESS!!! :-) I don't think thats the problem - rather I get the impression that there are references (and or resources) inside these SimpleXML objects (e.g. the owning 'document') that cannot be serialized. I would suggest caching the xml string and read that from disk (or where ever your storing stuff) and creating an object from that whenever you need it. I don't believe that you gain much from serializing an object (as compared to creating a new object) - when you unserialize you have pretty much the same overhead as when creating an object (I may be very wrong on this! - I do know that cloning an object is _much_ faster than creating one for instance). -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout? [Resolved]
Just replying to my original post as means of a follow up. I have gone ahead and used Rasmus' code, he was correct in surmising I was only worried about an overloaded and slow responding site. It would be very atypical for the site to be down completely. While the cache code was very interesting, I think it is a bit overkill considering the low amount of traffic my site receives. What I have done instead is to write the feed to a local file upon every update. I think it is more elegant to have an old feed than to have the terse Feed unavailable in the spot where the headlines should be. I have tested by setting the timeout to '0' rather than yanking my ethernet cable and it seems to work well. I just don't have a suitable spare box to try the ethernet method, and setting the timeout to 0 seems to have the intended effect anyway. Again, I just want to thank everybody involved for their time and effort, it is very much appreciated. Here is my function now, if anybody is interested: function getFeed($url) { $cache_version = $_SERVER['DOCUMENT_ROOT'] . /cache/ . basename($url); $rfd = fopen($url, 'r'); stream_set_blocking($rfd,true); stream_set_timeout($rfd, 5); // 5-second timeout $data = stream_get_contents($rfd); $status = stream_get_meta_data($rfd); fclose($rfd); if ($status['timed_out']) { $xml = simplexml_load_file($cache_version); } else { $lfd = fopen($cache_version, 'w'); fwrite($lfd, $data); fclose($lfd); $xml = simplexml_load_string($data); } print ul\n; foreach ($xml-channel-item as $item) { $cleaned = str_replace(, amp;, $item-link); print lia href='$cleaned'$item-title/a/li\n; } print /ul\n; } -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org ...the number of UNIX installations has grown to 10, with more expected... - Dennis Ritchie and Ken Thompson, June 1972 pgpSQRnWoXs98.pgp Description: PGP signature
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Here is an example Wez wrote years ago: -snip code - Years ago? stream_socket_client() is php5. How long ago did php5 launch? tedd -- http://sperling.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
tedd wrote: Here is an example Wez wrote years ago: -snip code - Years ago? stream_socket_client() is php5. How long ago did php5 launch? The first beta was in June 2003. But the streams code was written well before that. -Rasmus -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
At 10:31 AM -0700 4/11/06, Rasmus Lerdorf wrote: tedd wrote: Here is an example Wez wrote years ago: -snip code - Years ago? stream_socket_client() is php5. How long ago did php5 launch? The first beta was in June 2003. But the streams code was written well before that. -Rasmus I'm running php 4 and stream_socket_client() isn't there. So, I figured that the example written years ago, must have been as recent as php5. tedd -- http://sperling.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, April 10, 2006 10:21 pm, Robert Cummings wrote: On Mon, 2006-04-10 at 23:11, Richard Lynch wrote: On Mon, April 10, 2006 9:59 pm, Rasmus Lerdorf wrote: Richard Lynch wrote: I've added a Note to 'fopen' so maybe others won't completely miss this feature and look as foolish as I do right now. :-) If it's anything like the helpful note I added about using copy( source, dest ) where dest accidentally points to source (due to linking), you'll get a nice retarded email like the following: --- You are receiving this email because your note posted to the online PHP manual has been removed by one of the editors. I also have had what I still believe were actually quite useful comments deleted :-( And none of the reasoning in the stock form email applied, imho. It's an awfully long stretch or a very thin line between these: Feature Request: Documentation User Contrbuted Note I mean, the BEST User Contributed Notes probably qualify as Feature Requests to improve the Docs, no? Seems like those are the ones getting nuked, sometimes. Oh well. [shrug] Better than the alternative of having a lot of utter [bleep] in the User Contributed sections, I guess. Still, maybe an appeal or a reader-voting system would make more sense than a PHP Dev/Doc Team member copy-editing every note... Obviously you'd still want a Doc Team member stepping in at some point and just nuking anything blatantly wrong no matter how popular... -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, April 10, 2006 10:24 pm, Rasmus Lerdorf wrote: You could volunteer to help maintain the user notes. I've just spent five/ten minutes with Google and php.net trying to find the best way to volunteer to do just that... Admittedly not a LOT of effort, but... Where do I start? I do have one reservation, though... Last time I tried to do something like this, I ended up having a hard drive with what felt like Gigabytes of PHP Doc source code from CVS (which was an adventure in itself back then) and then had to attempt to run software that chewed up so much RAM/CPU and never managed to actually get useful output before crashing from lack of resources. Granted, this was a decade ago, and my hardware was pretty crappy at the time... Not that I've got much better gear now, mind you. :-) I'm guessing though that these days, it's just a web form somewhere. I can handle that. :-) Though it might finally be time for me to take another whack at PHP CVS development and see if I can't contribute even more... -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Richard Lynch wrote: On Mon, April 10, 2006 10:24 pm, Rasmus Lerdorf wrote: You could volunteer to help maintain the user notes. I've just spent five/ten minutes with Google and php.net trying to find the best way to volunteer to do just that... Admittedly not a LOT of effort, but... Where do I start? Start by reading http://php.net/dochowto Specifically chapter 11 - http://doc.php.net/php/dochowto/chapter-user-notes.php That should everyone here some insight into the user notes process. I do have one reservation, though... Last time I tried to do something like this, I ended up having a hard drive with what felt like Gigabytes of PHP Doc source code from CVS (which was an adventure in itself back then) and then had to attempt to run software that chewed up so much RAM/CPU and never managed to actually get useful output before crashing from lack of resources. Granted, this was a decade ago, and my hardware was pretty crappy at the time... Not that I've got much better gear now, mind you. :-) I'm guessing though that these days, it's just a web form somewhere. I can handle that. :-) For just auditing notes, you can do it via a web form, yes. And now with livedocs, you can get instant feedback if you want to progress to actually work on the main manual pages themselves. The above howto -Rasmus -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, 2006-04-10 at 15:25, darren kirby wrote: Hello all, My website uses simpleXML to print the headlines from a few different RSS feeds. The problem is that sometimes the remote feed is unavailable if there are problems with the remote site, and the result is that I must wait for 30 seconds or so until the HTTP timeout occurs, delaying the rendering of my site. So far, I have moved the code that grabs the RSS feeds to the bottom of my page, so that the main page content is rendered first, but this is only a partial solution. Is there a way to give the simplexml_load_file() a 5 second timeout before giving up and moving on? Here is my function: function getFeed($remote) { if (!$xml = simplexml_load_file($remote)) { print Feed unavailable; return; } print ul\n; foreach ($xml-channel-item as $item) { $cleaned = str_replace(, amp;, $item-link); print lia href='$cleaned'$item-title/a/li\n; } print /ul\n; } Why do you do this on every request? Why not have a cron job retrieve an update every 20 minutes or whatnot and stuff it into a database table for your page to access? Then if the cron fails to retrieve the feed it can just leave the table as is, and your visitors can happily view slightly outdated feeds? Additionally this will be so much faster that your users might even hang around on your site :) Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
quoth the Robert Cummings: Why do you do this on every request? Why not have a cron job retrieve an update every 20 minutes or whatnot and stuff it into a database table for your page to access? Then if the cron fails to retrieve the feed it can just leave the table as is, and your visitors can happily view slightly outdated feeds? Additionally this will be so much faster that your users might even hang around on your site :) This is a very interesting idea, but I am not sure if it is suitable for me at this point. First of all, one feed in particular can change in a matter of seconds, and I do want it to be as up to date as possible. Secondly, this is just for my personal site which is very low traffic, and it is not inconceivable that getting the feed every 20 minutes by cron would be _more_ taxing on the network than simply grabbing it per request... And to be fair, when everything is working as it should the feeds are retrieved in a matter of seconds, and I don't think it is annoying my users at all. It is the 0.5% of requests when the remote site is overloaded (or just plain down) that I want to provision for here. I do like this idea of caching the feed though. I think in my situation though, rather than prefetching the feed at regular intervals it may be better to cache the most recent request, and check the age of the cache when the next request comes. This way, I would not be needlessly updating it for those times when the page with my feeds goes for a few hours without a request. Of course, this still wouldn't solve my original problem. Cheers, Rob. -- Thanks for your insight, -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org ...the number of UNIX installations has grown to 10, with more expected... - Dennis Ritchie and Ken Thompson, June 1972 pgp80qbla946k.pgp Description: PGP signature
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, 2006-04-10 at 17:46, darren kirby wrote: quoth the Robert Cummings: Why do you do this on every request? Why not have a cron job retrieve an update every 20 minutes or whatnot and stuff it into a database table for your page to access? Then if the cron fails to retrieve the feed it can just leave the table as is, and your visitors can happily view slightly outdated feeds? Additionally this will be so much faster that your users might even hang around on your site :) This is a very interesting idea, but I am not sure if it is suitable for me at this point. First of all, one feed in particular can change in a matter of seconds, and I do want it to be as up to date as possible. Secondly, this is just for my personal site which is very low traffic, and it is not inconceivable that getting the feed every 20 minutes by cron would be _more_ taxing on the network than simply grabbing it per request... And to be fair, when everything is working as it should the feeds are retrieved in a matter of seconds, and I don't think it is annoying my users at all. It is the 0.5% of requests when the remote site is overloaded (or just plain down) that I want to provision for here. I do like this idea of caching the feed though. I think in my situation though, rather than prefetching the feed at regular intervals it may be better to cache the most recent request, and check the age of the cache when the next request comes. This way, I would not be needlessly updating it for those times when the page with my feeds goes for a few hours without a request. Of course, this still wouldn't solve my original problem. Well personal websites break all the rules. There's nobody to answer to but yourself :) Looks like simplexml neglected to offer a timeout option. You would probably be better off using curl to retrieve the content, then using simplexml_load_string(). Curl does allow you to assign a timeout. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
quoth the Robert Cummings: On Mon, 2006-04-10 at 17:46, darren kirby wrote: quoth the Robert Cummings: Why do you do this on every request? Why not have a cron job retrieve an update every 20 minutes or whatnot and stuff it into a database table for your page to access? Then if the cron fails to retrieve the feed it can just leave the table as is, and your visitors can happily view slightly outdated feeds? Additionally this will be so much faster that your users might even hang around on your site :) This is a very interesting idea, but I am not sure if it is suitable for me at this point. First of all, one feed in particular can change in a matter of seconds, and I do want it to be as up to date as possible. Secondly, this is just for my personal site which is very low traffic, and it is not inconceivable that getting the feed every 20 minutes by cron would be _more_ taxing on the network than simply grabbing it per request... And to be fair, when everything is working as it should the feeds are retrieved in a matter of seconds, and I don't think it is annoying my users at all. It is the 0.5% of requests when the remote site is overloaded (or just plain down) that I want to provision for here. I do like this idea of caching the feed though. I think in my situation though, rather than prefetching the feed at regular intervals it may be better to cache the most recent request, and check the age of the cache when the next request comes. This way, I would not be needlessly updating it for those times when the page with my feeds goes for a few hours without a request. Of course, this still wouldn't solve my original problem. Well personal websites break all the rules. There's nobody to answer to but yourself :) Looks like simplexml neglected to offer a timeout option. You would probably be better off using curl to retrieve the content, then using simplexml_load_string(). Curl does allow you to assign a timeout. That's the ticket! Thanks a lot for your help. Cheers, Rob. -d .. | InterJinn Application Framework - http://www.interjinn.com | | :: : | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org ...the number of UNIX installations has grown to 10, with more expected... - Dennis Ritchie and Ken Thompson, June 1972 pgp1pVIKLSoO2.pgp Description: PGP signature
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Maybe you can read the contents of the feeds using fsockopen() and stream_set_timeout() to adjust the timeout, or stream_set_blocking() to read it asynchronously, and then load the xml with simplexml_load_string(). PS: I forgot to reply to all and mention you'll have to send the GET http command and headers, check the php manual for examples. 2006/4/10, darren kirby [EMAIL PROTECTED]: Hello all, My website uses simpleXML to print the headlines from a few different RSS feeds. The problem is that sometimes the remote feed is unavailable if there are problems with the remote site, and the result is that I must wait for 30 seconds or so until the HTTP timeout occurs, delaying the rendering of my site. So far, I have moved the code that grabs the RSS feeds to the bottom of my page, so that the main page content is rendered first, but this is only a partial solution. Is there a way to give the simplexml_load_file() a 5 second timeout before giving up and moving on? Here is my function: function getFeed($remote) { if (!$xml = simplexml_load_file($remote)) { print Feed unavailable; return; } print ul\n; foreach ($xml-channel-item as $item) { $cleaned = str_replace(, amp;, $item-link); print lia href='$cleaned'$item-title/a/li\n; } print /ul\n; } PHP 5.1.2 on Linux. thanks, -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org ...the number of UNIX installations has grown to 10, with more expected... - Dennis Ritchie and Ken Thompson, June 1972 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
quoth the Martin Alterisio: Maybe you can read the contents of the feeds using fsockopen() and stream_set_timeout() to adjust the timeout, or stream_set_blocking() to read it asynchronously, and then load the xml with simplexml_load_string(). Hello, and thanks for the response, As Robert Cummings suggested above, the easy solution is to use curl, which does offer a timeout option, and then feed it to simplexml_load_string(). I am writing some code now... Thanks, and have a good one, -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org ...the number of UNIX installations has grown to 10, with more expected... - Dennis Ritchie and Ken Thompson, June 1972 pgpn7Z5Ag4G6c.pgp Description: PGP signature
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Martin Alterisio wrote: Maybe you can read the contents of the feeds using fsockopen() and stream_set_timeout() to adjust the timeout, or stream_set_blocking() to read it asynchronously, and then load the xml with simplexml_load_string(). PS: I forgot to reply to all and mention you'll have to send the GET http command and headers, check the php manual for examples. You can just use fopen() to avoid all that. eg. $fd = fopen($url); stream_set_blocking($fd,true); stream_set_timeout($fd, 5); // 5-second timeout $data = stream_get_contents($fd); $status = stream_get_meta_data($fd); if($status['timed_out']) echo Time out; else { $xml = simplexml_load_string($data); } As for your caching, make sure you create the cache file atomically. So how about this: function request_cache($url, $dest_file, $ctimeout=60, $rtimeout=5) { if(!file_exists($dest_file) || filemtime($dest_file) (time()-$ctimeout)) { $stream = fopen($url,'r'); stream_set_blocking($stream,true); stream_set_timeout($stream, $rtimeout); $tmpf = tempnam('/tmp','YWS'); file_put_contents($tmpf, $stream); fclose($stream); rename($tmpf, $dest_file); } } That takes the url to your feed, a destination file to cache to, a cache timeout (as in, fetch from the feed if the cache is older than 60 seconds) and finally the request timeout. Note the file_put_contents of the stream straight to disk, so you don't ever suck the file into memory. You can then use a SAX parser like xmlreader on it and your memory usage will be minimal. You will need PHP 5.1.x for this to work. You could also use apc_store/fetch and skip the disk copy altogether. (untested and typed up during a long boring meeting, so play with it a bit) -Rasmus -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, April 10, 2006 4:46 pm, darren kirby wrote: quoth the Robert Cummings: Why do you do this on every request? Why not have a cron job retrieve an update every 20 minutes or whatnot and stuff it into a database table for your page to access? Then if the cron fails to retrieve the feed it can just leave the table as is, and your visitors can happily view slightly outdated feeds? Additionally this will be so much faster that your users might even hang around on your site :) This is a very interesting idea, but I am not sure if it is suitable for me at this point. First of all, one feed in particular can change in a matter of seconds, and I do want it to be as up to date as possible. Secondly, this is just for my personal site which is very low traffic, and it is not inconceivable that getting the feed every 20 minutes by cron would be _more_ taxing on the network than simply grabbing it per request... Perhaps, then, you should: maintain a list of URLs and acceptable age of feed. Attempt to snag the new content upon visit, if the content is old Show the old content if the feed takes longer than X seconds. You'll STILL need a timeout, which, unfortunately, means you are stuck rolling your own solution with http://php.net/fsockopen because all the simple solutions pretty much suck in terms of network timeout. :-( It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( Since I've already written a class that does something like what you want, or maybe even exactly what you want, I might as well just provide the source, eh? http://l-i-e.com/FeedMulti/FeedMulti.phps -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, April 10, 2006 6:17 pm, Rasmus Lerdorf wrote: Martin Alterisio wrote: Maybe you can read the contents of the feeds using fsockopen() and stream_set_timeout() to adjust the timeout, or stream_set_blocking() to read it asynchronously, and then load the xml with simplexml_load_string(). PS: I forgot to reply to all and mention you'll have to send the GET http command and headers, check the php manual for examples. You can just use fopen() to avoid all that. No, he can't. Sorry, Rasmus. :-) If the URL is not working at the time of fopen() then you'll sit there spinning your wheels waiting for fopen() itself to timeout, before you ever GET a valid file handle to which one can apply stream_set_timeout and/or stream_set_blocking. That can take MUCH too long. So you're STUCK with fsockopen, which DOES take a timeout parameter for OPENING the socket, as well as giving one a stream to which stream_set_blocking and stream_set_timeout can be applied. But then you are stuck re-inventing the damn wheel with any protocol you'd like to support like GET/POST, HTTPS (ugh!), FTP and so on. All of which is buried in the guts of the Truly Nifty fopen, file_get_contents, and so forth, but is utterly useless if you care at all about timing out in a reasonably-responsive application. So you have do all the junk to send things like: GET / HTTP/1.0 Host: example.com yourself, and God help you if you want to support HTTPS. Actually, curl MAY be the better solution -- but my boss doesn't have curl installed, so I was screwed anyway... This is why I (and others) have put in a Feature Request to get fopen() and friends to have some kind of programmatically changable timeout setting. Said Feature Requests invariably get marked Bogus and then commented with something like the non-solution above. :-) Oh well. It *can* be done; You just have to type WAY too much junk to do something very simple and very commonly needed. -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
quoth the Richard Lynch: Perhaps, then, you should: maintain a list of URLs and acceptable age of feed. Attempt to snag the new content upon visit, if the content is old Show the old content if the feed takes longer than X seconds. I really do like this idea, as I would rather use an old feed than just print Feed unavailable as I have it now. You'll STILL need a timeout, which, unfortunately, means you are stuck rolling your own solution with http://php.net/fsockopen because all the simple solutions pretty much suck in terms of network timeout. :-( It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( I am interested, but I don't have the skills either... Since I've already written a class that does something like what you want, or maybe even exactly what you want, I might as well just provide the source, eh? http://l-i-e.com/FeedMulti/FeedMulti.phps Thanks for that, it looks like interesting code, if not a little over my head. I am just a duffer here. I will certainly play with it some more. As for curl, I realized I didn't add curl support myself, so I am rebuilding PHP now... When I do get something figured out I will post results here. Problem is, with either method I need to find a feed that is slow to test with. If I test it with a bunk url it will just 404 immediately right? Is there a way to simulate a slow connection? -- Like Music? http://l-i-e.com/artists.htm Thanks a lot for the help, everybody! -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org ...the number of UNIX installations has grown to 10, with more expected... - Dennis Ritchie and Ken Thompson, June 1972 pgp8eJbTMrXbb.pgp Description: PGP signature
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, 2006-04-10 at 20:52, darren kirby wrote: quoth the Richard Lynch: Perhaps, then, you should: maintain a list of URLs and acceptable age of feed. Attempt to snag the new content upon visit, if the content is old Show the old content if the feed takes longer than X seconds. I really do like this idea, as I would rather use an old feed than just print Feed unavailable as I have it now. You'll STILL need a timeout, which, unfortunately, means you are stuck rolling your own solution with http://php.net/fsockopen because all the simple solutions pretty much suck in terms of network timeout. :-( It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( I am interested, but I don't have the skills either... Since I've already written a class that does something like what you want, or maybe even exactly what you want, I might as well just provide the source, eh? http://l-i-e.com/FeedMulti/FeedMulti.phps Thanks for that, it looks like interesting code, if not a little over my head. I am just a duffer here. I will certainly play with it some more. As for curl, I realized I didn't add curl support myself, so I am rebuilding PHP now... When I do get something figured out I will post results here. Problem is, with either method I need to find a feed that is slow to test with. If I test it with a bunk url it will just 404 immediately right? Is there a way to simulate a slow connection? For sure ;) Pull your ethernet cable out. Doesn't get much slower :D Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
When I do get something figured out I will post results here. Problem is, with either method I need to find a feed that is slow to test with. If I test it with a bunk url it will just 404 immediately right? Is there a way to simulate a slow connection? I dunno about similating a slow connection, but you can write a very slow server... :-) my_slow_rss_feed.php ?php $data = 'nameDarren Kirby/name'; sleep(10); for ($i = 0; $i strlen($data); $i++){ echo $data[$i]; flush(); sleep(1); } ? Of course, that doesn't simulate the slow connection part of it... If you have 2 machines, you can unplug the network cable, start your script, then plug the cable in after 5 seconds. That's gonna make it pretty slow to connect, almost for sure. :-) If anybody is goofy enough to complain about the performance of strlen() in the for(...) statement, you're clearly not paying attention. :-) :-) :-) -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Maybe it's too late to say this, but if your real problem is that you don't want the function reading the rss feed to block the rest of your page, you can always put the output of the reading of the feed on a separate page, and include this through an iframe. darren kirby wrote: Hello all, My website uses simpleXML to print the headlines from a few different RSS feeds. The problem is that sometimes the remote feed is unavailable if there are problems with the remote site, and the result is that I must wait for 30 seconds or so until the HTTP timeout occurs, delaying the rendering of my site. So far, I have moved the code that grabs the RSS feeds to the bottom of my page, so that the main page content is rendered first, but this is only a partial solution. Is there a way to give the simplexml_load_file() a 5 second timeout before giving up and moving on? Here is my function: function getFeed($remote) { if (!$xml = simplexml_load_file($remote)) { print Feed unavailable; return; } print ul\n; foreach ($xml-channel-item as $item) { $cleaned = str_replace(, amp;, $item-link); print lia href='$cleaned'$item-title/a/li\n; } print /ul\n; } PHP 5.1.2 on Linux. thanks, -d -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Richard Lynch wrote: On Mon, April 10, 2006 6:17 pm, Rasmus Lerdorf wrote: Martin Alterisio wrote: Maybe you can read the contents of the feeds using fsockopen() and stream_set_timeout() to adjust the timeout, or stream_set_blocking() to read it asynchronously, and then load the xml with simplexml_load_string(). PS: I forgot to reply to all and mention you'll have to send the GET http command and headers, check the php manual for examples. You can just use fopen() to avoid all that. No, he can't. Sorry, Rasmus. :-) If the URL is not working at the time of fopen() then you'll sit there spinning your wheels waiting for fopen() itself to timeout, before you ever GET a valid file handle to which one can apply stream_set_timeout and/or stream_set_blocking. I thought it was the case of an overloaded slow-responding server, not one that is down. For the initial connection just set your default_socket_timeout appropriately if you are not happy with the default. So you just add 1 line to my example: function request_cache($url, $dest_file, $ctimeout=60, $rtimeout=5) { if(!file_exists($dest_file) || filemtime($dest_file) (time()-$ctimeout)) { ini_set('default_socket_timeout',$rtimeout); $stream = fopen($url,'r'); stream_set_blocking($stream,true); stream_set_timeout($stream, $rtimeout); $tmpf = tempnam('/tmp','YWS'); file_put_contents($tmpf, $stream); fclose($stream); rename($tmpf, $dest_file); } } Problem solved. -Rasmus -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Richard Lynch wrote: It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( Because it is already there and has been since Sept.23 2002 when it was added. -Rasmus -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, April 10, 2006 9:59 pm, Rasmus Lerdorf wrote: Richard Lynch wrote: It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( Because it is already there and has been since Sept.23 2002 when it was added. I've added a Note to 'fopen' so maybe others won't completely miss this feature and look as foolish as I do right now. :-) -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Richard Lynch wrote: On Mon, April 10, 2006 4:46 pm, darren kirby wrote: quoth the Robert Cummings: Why do you do this on every request? Why not have a cron job retrieve an update every 20 minutes or whatnot and stuff it into a database table for your page to access? Then if the cron fails to retrieve the feed it can just leave the table as is, and your visitors can happily view slightly outdated feeds? Additionally this will be so much faster that your users might even hang around on your site :) This is a very interesting idea, but I am not sure if it is suitable for me at this point. First of all, one feed in particular can change in a matter of seconds, and I do want it to be as up to date as possible. Secondly, this is just for my personal site which is very low traffic, and it is not inconceivable that getting the feed every 20 minutes by cron would be _more_ taxing on the network than simply grabbing it per request... Perhaps, then, you should: maintain a list of URLs and acceptable age of feed. Attempt to snag the new content upon visit, if the content is old Show the old content if the feed takes longer than X seconds. You'll STILL need a timeout, which, unfortunately, means you are stuck rolling your own solution with http://php.net/fsockopen because all the simple solutions pretty much suck in terms of network timeout. :-( It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( Since I've already written a class that does something like what you want, or maybe even exactly what you want, I might as well just provide the source, eh? http://l-i-e.com/FeedMulti/FeedMulti.phps No stream_select() ? Here is an example Wez wrote years ago: ?php $hosts = array(host1.sample.com, host2.sample.com, host3.sample.com); $timeout = 15; $status = array(); $sockets = array(); /* Initiate connections to all the hosts simultaneously */ foreach ($hosts as $id = $host) { $s = stream_socket_client($host:80, $errno, $errstr, $timeout, STREAM_CLIENT_ASYNC_CONNECT); if ($s) { $sockets[$id] = $s; $status[$id] = in progress; } else { $status[$id] = failed, $errno $errstr; } } /* Now, wait for the results to come back in */ while (count($sockets)) { $read = $write = $sockets; /* This is the magic function - explained below */ $n = stream_select($read, $write, $e = null, $timeout); if ($n 0) { /* readable sockets either have data for us, or are failed * connection attempts */ foreach ($read as $r) { $id = array_search($r, $sockets); $data = fread($r, 8192); if (strlen($data) == 0) { if ($status[$id] == in progress) { $status[$id] = failed to connect; } fclose($r); unset($sockets[$id]); } else { $status[$id] .= $data; } } /* writeable sockets can accept an HTTP request */ foreach ($write as $w) { $id = array_search($w, $sockets); fwrite($w, HEAD / HTTP/1.0\r\nHost: . $hosts[$id] . \r\n\r\n); $status[$id] = waiting for response; } } else { /* timed out waiting; assume that all hosts associated * with $sockets are faulty */ foreach ($sockets as $id = $s) { $status[$id] = timed out . $status[$id]; } break; } } foreach ($hosts as $id = $host) { echo Host: $host\n; echo Status: . $status[$id] . \n\n; } ? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, 2006-04-10 at 23:11, Richard Lynch wrote: On Mon, April 10, 2006 9:59 pm, Rasmus Lerdorf wrote: Richard Lynch wrote: It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( Because it is already there and has been since Sept.23 2002 when it was added. I've added a Note to 'fopen' so maybe others won't completely miss this feature and look as foolish as I do right now. :-) If it's anything like the helpful note I added about using copy( source, dest ) where dest accidentally points to source (due to linking), you'll get a nice retarded email like the following: --- You are receiving this email because your note posted to the online PHP manual has been removed by one of the editors. Read the following paragraphs carefully, because they contain pointers to resources better suited for requesting support or reporting bugs, none of which are to be included in manual notes because there are mechanisms and groups in place to deal with those issues. The user contributed notes are not an appropriate place to ask questions, report bugs or suggest new features; please use the resources listed on http://php.net/support for those purposes. This was clearly stated in the page you used to submit your note, please carefully re-read those instructions before submitting future contributions. Bug submissions and feature requests should be entered at http://bugs.php.net/. For documentation errors use the bug system, and classify the bug as Documentation problem. Support and ways to find answers to your questions can be found at http://php.net/support. Your note has been removed from the online manual. - Copy of your note below - User tip... it can be completely befuddling if you don't realize your source and destination files are the same (this can happen with directory links). When this happens there are a couple of possibilities... at first I was using php 4.4.0 and the files just became 0 length. The second, outcome after I upgraded to 4.4.2 (since I didn't realize the problem) was that the copy function returned a failure. This was tricky to track since there's no error output indicating why the copy failed :) -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Robert Cummings wrote: On Mon, 2006-04-10 at 23:11, Richard Lynch wrote: On Mon, April 10, 2006 9:59 pm, Rasmus Lerdorf wrote: Richard Lynch wrote: It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( Because it is already there and has been since Sept.23 2002 when it was added. I've added a Note to 'fopen' so maybe others won't completely miss this feature and look as foolish as I do right now. :-) If it's anything like the helpful note I added about using copy( source, dest ) where dest accidentally points to source (due to linking), you'll get a nice retarded email like the following: You could volunteer to help maintain the user notes. It it thankless and tedious work to keep up with the flood of user notes being submitted. A huge percentage of them being either spam, product pitches or really dumb questions. The fact that occasionally a useful note gets deleted by mistake doesn't surprise me. -Rasmus -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, 2006-04-10 at 23:35, Rasmus Lerdorf wrote: Robert Cummings wrote: I'll keep that in mind for the future when I have more free time (2 kids under 3 is good for keeping me occupied beyond work atm :). A huge percentage of them being either spam, product pitches or really dumb questions. The fact that occasionally a useful note gets deleted by mistake doesn't surprise me. Point taken, just sort of feels like slap in the face after you go to the effort to write a useful note :) Yes, but just keep in mind that the folks on the other end make the effort every single day to cull through hundreds of these. We have small kids and real jobs as well. I am typing this with a 4-year old sitting in my lap doing his best to make a dinosaur stomp on my keys. Ummm, that was a sincere I'll keep it in mind. And I know all about typing away with a newborn sleeping on my chest, a 1 year old pawing the screen, a 2 year old mashing the keys and cackling mischievously. So while I sympathize with the fact that the work you put into this note wasn't appreciated, please recognize that you are not being very appreciative of the hundreds of hours of work the folks on the other end are putting in. I'm very appreciative, but at the same time, I don't feel like I shouldn't comment on the potential of getting your note trashed like so much spam. Don't forget, adding a note IS contributing. I usually add as I see fit, I've added in the past, I'm sure I'll add in the future. But now I'm a little on the twice shy side of the coin. In general the user notes in the manual are useful. There isn't much spam, and when something slips through it gets caught rather quickly. This stuff doesn't happen by itself. Exactly, it doesn't happen by itself, neither do the notes. It's a dovetailing arrangement. People add notes, people trim spam. It takes both for either system to work. Agreed, though that adding notes isn't the same as spending countless hours pruning. Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
On Mon, 2006-04-10 at 23:24, Rasmus Lerdorf wrote: Robert Cummings wrote: On Mon, 2006-04-10 at 23:11, Richard Lynch wrote: On Mon, April 10, 2006 9:59 pm, Rasmus Lerdorf wrote: Richard Lynch wrote: It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( Because it is already there and has been since Sept.23 2002 when it was added. I've added a Note to 'fopen' so maybe others won't completely miss this feature and look as foolish as I do right now. :-) If it's anything like the helpful note I added about using copy( source, dest ) where dest accidentally points to source (due to linking), you'll get a nice retarded email like the following: You could volunteer to help maintain the user notes. It it thankless and tedious work to keep up with the flood of user notes being submitted. I'll keep that in mind for the future when I have more free time (2 kids under 3 is good for keeping me occupied beyond work atm :). A huge percentage of them being either spam, product pitches or really dumb questions. The fact that occasionally a useful note gets deleted by mistake doesn't surprise me. Point taken, just sort of feels like slap in the face after you go to the effort to write a useful note :) Cheers, Rob. -- .. | InterJinn Application Framework - http://www.interjinn.com | :: | An application and templating framework for PHP. Boasting | | a powerful, scalable system for accessing system services | | such as forms, properties, sessions, and caches. InterJinn | | also provides an extremely flexible architecture for | | creating re-usable components quickly and easily. | `' -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] simpleXML - simplexml_load_file() timeout?
Robert Cummings wrote: On Mon, 2006-04-10 at 23:24, Rasmus Lerdorf wrote: Robert Cummings wrote: On Mon, 2006-04-10 at 23:11, Richard Lynch wrote: On Mon, April 10, 2006 9:59 pm, Rasmus Lerdorf wrote: Richard Lynch wrote: It would be REALLY NIFTY if fopen and friends which understand all those protocols of HTTP FTP HTTPS and so on, allowed one to set a timeout for URLs, but they don't and nobody with the skills to change that (not me) seems even mildly interested. :-( :-( :-( Because it is already there and has been since Sept.23 2002 when it was added. I've added a Note to 'fopen' so maybe others won't completely miss this feature and look as foolish as I do right now. :-) If it's anything like the helpful note I added about using copy( source, dest ) where dest accidentally points to source (due to linking), you'll get a nice retarded email like the following: You could volunteer to help maintain the user notes. It it thankless and tedious work to keep up with the flood of user notes being submitted. I'll keep that in mind for the future when I have more free time (2 kids under 3 is good for keeping me occupied beyond work atm :). A huge percentage of them being either spam, product pitches or really dumb questions. The fact that occasionally a useful note gets deleted by mistake doesn't surprise me. Point taken, just sort of feels like slap in the face after you go to the effort to write a useful note :) Yes, but just keep in mind that the folks on the other end make the effort every single day to cull through hundreds of these. We have small kids and real jobs as well. I am typing this with a 4-year old sitting in my lap doing his best to make a dinosaur stomp on my keys. So while I sympathize with the fact that the work you put into this note wasn't appreciated, please recognize that you are not being very appreciative of the hundreds of hours of work the folks on the other end are putting in. In general the user notes in the manual are useful. There isn't much spam, and when something slips through it gets caught rather quickly. This stuff doesn't happen by itself. -Rasmus -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML
On Wed, January 18, 2006 3:49 pm, Jay Paulson wrote: I'm a noob when it comes to parsing an XML file. I have a really simple file that I'm getting back from a SOAP service that I need to parse. I figure SimpleXML would be great! However, I'm having problems getting the name attribute for each column element. The XML is below along with the code I'm using to parse it. $xml = XML resultSet recordCount=3 columnCount=4 record column name=BUSINESS_UNITCE/column column name=ATTENDANCEC/column column name=COUNT(A.EMPLID)1/column column name=TO_CHAR(SYSDATE,-MM-DD)2006-01-18/column /record record column name=BUSINESS_UNITCE/column column name=ATTENDANCED/column column name=COUNT(A.EMPLID)1/column column name=TO_CHAR(SYSDATE,-MM-DD)2006-01-18/column /record record column name=BUSINESS_UNITCE/column column name=ATTENDANCEE/column column name=COUNT(A.EMPLID)5/column column name=TO_CHAR(SYSDATE,-MM-DD)2006-01-18/column /record /resultSet XML; $xml = simplexml_load_string($xml); print_r($xml); foreach ($xml-record as $record) { foreach ($xml-record as $key = $record){ echo $key, : br /\n; list($k, $v) = each($xml-record-$key-attributes()); echo {$k} = {$v}br; echo {$key} key / {$value} valuehr; } } -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML returning Object names with hyphens
Charlie Davis wrote: Hey all, I've run into a snag trying to use some XML output from NOAA. what NOAA when its at home? The problem is that some of the fields it sends to me have a hyphen in the name. Simple XML then creates objects with hyphens in their name. So here's the object I am having issues with: object(SimpleXMLElement)#7 (2) { wind-speed = object(SimpleXMLElement)#9 (2) { name = string(10) Wind Speed value = array(37) { 0 = string(1) 4 1 = string(1) 4 ... 33 = string(3) 328 34 = string(3) 338 35 = string(3) 350 36 = string(3) 350 you could have trimmed that down a bit. } } } And here's my code issues: $xmlobj-data-parameters-direction access works fine. $xmlobj-data-parameters-direction-value works fine. Gives me the array. first turn up error reporting to full error_reporting( E_ALL | E_STRICT ); $xmlobj-data-parameters-wind-speed returns an int value of 0. $xmlobj-data-parameters-wind-speed-value gives me an error: then try something like (I'm guessing this might work, then again the behaviour of simpleXML [especially auto/magic casting] is greek to me): $xmlobj-data-parameters-{'wind-speed'} $xmlobj-data-parameters-{'wind-speed'}-value Parse error: parse error, unexpected T_OBJECT_OPERATOR in noaa.php on line 59 So, what am I doing wrong? The only thing I can think of is the - in the wind-speed object name. Any help would be appreciated! -Charlie -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML returning Object names with hyphens
Sweet. Thanks! The {'..'} works perfectly. Never knew about that syntax. -Charlie Jochem Maas wrote: Charlie Davis wrote: Hey all, I've run into a snag trying to use some XML output from NOAA. what NOAA when its at home? The problem is that some of the fields it sends to me have a hyphen in the name. Simple XML then creates objects with hyphens in their name. So here's the object I am having issues with: object(SimpleXMLElement)#7 (2) { wind-speed = object(SimpleXMLElement)#9 (2) { name = string(10) Wind Speed value = array(37) { 0 = string(1) 4 1 = string(1) 4 ... 33 = string(3) 328 34 = string(3) 338 35 = string(3) 350 36 = string(3) 350 you could have trimmed that down a bit. } } } And here's my code issues: $xmlobj-data-parameters-direction access works fine. $xmlobj-data-parameters-direction-value works fine. Gives me the array. first turn up error reporting to full error_reporting( E_ALL | E_STRICT ); $xmlobj-data-parameters-wind-speed returns an int value of 0. $xmlobj-data-parameters-wind-speed-value gives me an error: then try something like (I'm guessing this might work, then again the behaviour of simpleXML [especially auto/magic casting] is greek to me): $xmlobj-data-parameters-{'wind-speed'} $xmlobj-data-parameters-{'wind-speed'}-value Parse error: parse error, unexpected T_OBJECT_OPERATOR in noaa.php on line 59 So, what am I doing wrong? The only thing I can think of is the - in the wind-speed object name. Any help would be appreciated! -Charlie -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML doesn't work with one single XML tag line...
On 7/15/05, Daevid Vincent [EMAIL PROTECTED] wrote: Maybe I'm missing something about XML specifications, but this doesn't seem right to me. http://www.php.net/manual/en/ref.simplexml.php Here is a code fragment I use: $xml = simplexml_load_string($returnData); var_dump($xml); if (is_object($xml)) { //first lets make sure we didn't get an ERROR if ($xml-error) { echo An ERROR was encountered\n; echo CODE: .((string)$xml-error-code).\n; echo STRING: .((string)$xml-error-string).\n; exit; } ... } I have my XML setup such that if there is an error, I return: ?xml version=1.0 encoding=iso-8859-1 ? error code=tbd string=user not found. / this are attributes, which have to accessed differently. and the first object you get is already the root node (error in your case). try echo CODE: .((string)$xml['code']).\n; (not tested, but should work) chregu But simple XML will not detect this as illustrated by var_dump($xml) object(SimpleXMLElement)#1 (0) { } However, if I change my output to be: ?xml version=1.0 encoding=iso-8859-1 ? error codetbd/code stringuser not found with those credentials./string /error Then I get... object(SimpleXMLElement)#1 (2) { [code]= string(3) tbd [string]= string(38) user not found. } Notice also that my object is not nested inside an [error] as I would expect it to be. So I would expect to get this (in BOTH cases actually): object(SimpleXMLElement)#1 (1) { [error]= object(SimpleXMLElement)#1 (2) { [code]= string(3) tbd [string]= string(38) user not found. } } More useful information: [EMAIL PROTECTED]:/lockdown/includes/api# php -v PHP 5.0.3 (cli) (built: Jul 11 2005 12:33:48) Copyright (c) 1997-2004 The PHP Group Zend Engine v2.0.3, Copyright (c) 1998-2004 Zend Technologies with Zend Extension Manager v1.0.6, Copyright (c) 2003-2004, by Zend Technologies with Zend Optimizer v2.5.7, Copyright (c) 1998-2004, by Zend Technologies -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- christian stocker | Bitflux GmbH | schoeneggstrasse 5 | ch-8004 zurich phone +41 1 240 56 70 | mobile +41 76 561 88 60 | fax +41 1 240 56 71 http://www.bitflux.ch | [EMAIL PROTECTED] | gnupg-keyid 0x5CE1DECB -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SIMPLExml problem....
On Mon, Jun 20, 2005 at 10:48:41AM +0200, Cruonit wrote: I tryed this simple PHP script that uses SimpleXML control: snip In future, please don't post the same thing to the list three times, there really is no point. If your post isn't showing up, at least have the patience to wait a few minutes before re-sending if you think it hasn't got through. Paul -- Rogue Tory http://www.roguetory.org.uk -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SIMPLExml problem....
Cruonit wrote: I tryed this simple PHP script that uses SimpleXML control: ?php $users = simplexml_load_file('baza.xml'); echo $users - name; ? and i got: Fatal error: Cannot clone object of class SimpleXMLElement due to 'zend.ze1_compatibility_mode' in /mnt/storage/users/w/i/p/wipe/formular.php on line 381 a, zend.ze1_compatibility_mode is a php.ini setting - it needs to off in your case. b, your test script is 3 lines ... which begs the question of where the other 378 lines are? are you maybe using auto_prepend to include stuff automatically? i tryed the same code on 3 other servers including my localhost and it works (the versions where PHP 5.04 and on the server with the problem it's 5.03) i searched google but i didn't got the answer... http://wipe.host.sk http://bihnet.org/Cruonit/wipe/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SIMPLExml problem....
Cruonit wrote: I just copy/paste the error from other code, but i talked to the admin and he said I might suggest that reading the error (and maybe reseaching the meaning - if you don't understand what it means) ... read this: http://www.php.net/manual/en/ini.core.php now assuming your simpleXML code is not including any shite from phpNuke etc (stuff that relies on php4 object behaviour) you can set the zend.ze1_compatibility_mode to Off/0 in either a .htaccess file or in the virtualhost directive or elsewhere ... zend.ze1_compatibility_mode falls under PHP_INI_ALL which means you can even set it in your script: Table H-2. Definition of PHP_INI_* constants ConstantValue Meaning PHP_INI_USER1 Entry can be set in user scripts or in Windows registry PHP_INI_PERDIR 2 Entry can be set in php.ini, .htaccess or httpd.conf PHP_INI_SYSTEM 4 Entry can be set in php.ini or httpd.conf PHP_INI_ALL 7 Entry can be set anywhere - actually it means you can turn the value on and off countless times inside a script depending on which code/objects are being used/accessed/etc - but I have a funny feeling that if I combined some simeplXML code with some phpNuke code and made it switch ze1_compatibility_mode as required that it wouldn't work very well... but then again its completely untested. we can't set it off because then all PHP-4 written object code would be not functional. thats not true perse. alot of php4 OO codes works as-is. That means 99% of all code (all these forums, CMS - phpNuke, phpBB) -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML and xpath woes
On Wed, March 16, 2005 9:39 am, Simon Turvey said: (Apologies for the larger than normal wrapping - there are some long lines) I'm playing with SimpleXML for reading REST responses from Amazon Web Services. Having successfuly read the response to my request I'd like to perform an xpath query on the result. I've pared down the original response to a static XML file for testing purposes containing the following: WILD GUESS: The static XML you have saved is out-dated from their session/whatever?... -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML add a node
@richard I dunno about that whole try/catch thing, but if you're not going to USE it to catch the errors, then you might as well be old school and check the return values of all these functions. that sounds good, but , so far I know, if the API says that a function _can_ throw an exception, I _must_ catch it. In this case 'importNode', 'appendChild', and 'createElement'. If I'm wrong please correct me. Since it works once and not the second time, I'd be looking to see if the XML produced on the first go-around is actually VALID, since, if it's not, that would cause this problem, I think. The first time 'dom_import_simplexml' returns a DOMElement, the second a DOMDocument. I don't know why. The string version of the first SimpleXML is: (that produces a DOMElement) ?xml version=1.0?config/ The string version of the second SimpleXML is: (that produce a DOMDocument) ?xml version=1.0?configactive/config/ @jason I'm alredy using the 'dom_import_simplexml' function (line 5, code anexed) @jochem 'instanceof' used now, thanks for reminding. Also if in this case it wasn't the prpblem. last of all, a probalbly readable version of the code: --- // check if there is a valid simplexml document if (!($this-configXML instanceof SimpleXMLElement)) $this-createConfigXML(); $dom = new DOMDocument('1.0'); // create a DOMElement from SimpleXML $domElem = dom_import_simplexml($this-configXML); if ( $domElem === false ) return false; echo \n\r.'1:';var_dump($domElem);echo BR\n\r; try { // import DOMElement(simplexml) to empty DOMDocument $domNode = $dom-importNode($domElem,true); if ( $domNode === false ) return false; // append the imported node to the DOMDocument $domNode = $dom-appendChild($domNode); // create new DOMElement $domElem = $dom-createElement(($mode? 'softactive':'active')); // add new Element to DOMElement(simplexml) $domNode-appendChild( $domElem ); } catch(Exception $e) { echo 'EXCEPTION: '.$e-getMessage().'BR/'; return false; } // redefine old simplexml $simplexml = simplexml_import_dom($dom); if ($simplexml === false) return false; $this-configXML = $simplexml; echo '2:';echo $this-configXML-asXML();echo BR\n\r; } return true; -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML add a node
Richard Lynch wrote: php.net/dom ?? Like this? --- try { $dom = new DOMDocument(); $config = $dom-appendChild($dom-importNode(dom_import_simplexml($this-configXML),true)); $config-appendChild( $dom-createElement(($mode? 'softactive':'active')) ); $this-configXML = simplexml_import_dom($config); } catch(Exception $e) {} I dunno about that whole try/catch thing, but if you're not going to USE it to catch the errors, then you might as well be old school and check the the try/catch block only catch exceptions, you still have to handle the std errors as normally would - for the old school its business as usual, only this simester there are a couple of new kids in the class :-). I'm pretty sure there was alot of discussion about whether to throw exceptions or trigger errors in the new php5 extensions. I can't actually think of any place in php5 or the extensions I use where the engine throws an Exceptions... at any rate all my Exceptions are userland generated. like for instance when any object is not of the right class I might throw an Exception. Exceptions are really cool, but they are not are a replacement for var error checking. behold the 'instanceof' keyword. it is good :-) (free tip: javascript has a 'instanceof' keyword that is indentical to the php keyword in usage, AFAICT). the rest (xml) is all french to me :-/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML add a node
Jochem Maas wrote: Richard Lynch wrote: php.net/dom ?? Like this? --- try { $dom = new DOMDocument(); $config = $dom-appendChild($dom-importNode(dom_import_simplexml($this-configXML),true)); $config-appendChild( $dom-createElement(($mode? 'softactive':'active')) ); $this-configXML = simplexml_import_dom($config); } catch(Exception $e) {} I dunno about that whole try/catch thing, but if you're not going to USE it to catch the errors, then you might as well be old school and check the the try/catch block only catch exceptions, you still have to handle the std errors as normally would - for the old school its business as usual, only this simester there are a couple of new kids in the class :-). I'm pretty sure there was alot of discussion about whether to throw exceptions or trigger errors in the new php5 extensions. I can't actually think of any place in php5 or the extensions I use where the engine throws an Exceptions... I happened upon atleast one place where you can have the engine throw Exceptions iso triggering errors this: $db-setAttribute( PDO_ATTR_ERRMODE, PDO_ERRMODE_EXCEPTION ); I found here; http://wiki.cc/php/PDO_Basics ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML add a node
php.net/dom -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML add a node
php.net/dom ?? Like this? --- try { $dom = new DOMDocument(); $config = $dom-appendChild($dom-importNode(dom_import_simplexml($this-configXML),true)); $config-appendChild( $dom-createElement(($mode? 'softactive':'active')) ); $this-configXML = simplexml_import_dom($config); } catch(Exception $e) {} It ist strange... It runs one time, the second time I receive the following error. Warning: DOMDocument::importNode() [function.importNode]: Cannot import: Node Type Not Supported in ... Warning: appendChild() expects parameter 1 to be DOMNode, boolean given in ... Fatal error: Call to a member function appendChild() on a non-object in ... -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML add a node
php.net/dom ?? Like this? --- try { $dom = new DOMDocument(); $config = $dom-appendChild($dom-importNode(dom_import_simplexml($this-configXML),true)); $config-appendChild( $dom-createElement(($mode? 'softactive':'active')) ); $this-configXML = simplexml_import_dom($config); } catch(Exception $e) {} I dunno about that whole try/catch thing, but if you're not going to USE it to catch the errors, then you might as well be old school and check the return values of all these functions. It ist strange... It runs one time, the second time I receive the following error. Since it works once and not the second time, I'd be looking to see if the XML produced on the first go-around is actually VALID, since, if it's not, that would cause this problem, I think. Warning: DOMDocument::importNode() [function.importNode]: Cannot import: Node Type Not Supported in ... So what's the Node Type (whatever that is) of the Node you are importing? Warning: appendChild() expects parameter 1 to be DOMNode, boolean given in ... Fatal error: Call to a member function appendChild() on a non-object in ... -- Like Music? http://l-i-e.com/artists.htm -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML add a node
Richard Lynch wrote: ... } catch(Exception $e) {} I dunno about that whole try/catch thing, but if you're not going to USE it to catch the errors, then you might as well be old school and check the return values of all these functions. Agreed 100%. No sense in going through the overhead of creating Exceptions (which are objects BTW) if you're not even going to use it in any way at all. Exceptions take a lot of work to build / manage so for small projects it's really not even worth the time. It ist strange... It runs one time, the second time I receive the following error. Since it works once and not the second time, I'd be looking to see if the XML produced on the first go-around is actually VALID, since, if it's not, that would cause this problem, I think. A good point. Not only that... if you are trying to convert from simpleXML to DOM then you need dom_import_simplexml() http://php.net/manual/en/function.dom-import-simplexml.php -- Teach a man to fish... NEW? | http://www.catb.org/~esr/faqs/smart-questions.html STFA | http://marc.theaimsgroup.com/?l=php-generalw=2 STFM | http://php.net/manual/en/index.php STFW | http://www.google.com/search?q=php LAZY | http://mycroft.mozdev.org/download.html?name=PHPsubmitform=Find+search+plugins signature.asc Description: OpenPGP digital signature
Re: [PHP] SimpleXML: DOM, SAX or Other?
Hi On 15 Oct 2004 11:51:33 -, PHPDiscuss - PHP Newsgroups and mailing lists [EMAIL PROTECTED] wrote: Hi, Does anybody have any depthful knowledge of the SimpleXML extension in PHP5?.. More accurately, do you know if the simpleXml-xpath() method uses DOM, SAX or some other method of parsing a loaded XML document? I ask because I am trying to parse arbitrary XML documents as efficiently as possible (avoiding DOM). Hi SimpleXML uses the same stuff as DOM in the backend. So you won't gain any efficency using SimpleXML chregu Kieran -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- christian stocker | Bitflux GmbH | schoeneggstrasse 5 | ch-8004 zurich phone +41 1 240 56 70 | mobile +41 76 561 88 60 | fax +41 1 240 56 71 http://www.bitflux.ch | [EMAIL PROTECTED] | gnupg-keyid 0x5CE1DECB -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] simplexml and xpath
So I've just recently fallen in love with simplexml. But from what I've read, is it true that xpath doesn't really work properly? I'm using an XML file that has a section like this: item titleTitle/title linkLink/link descriptionDesc/description dc:subjectSubject/dc:subject dc:date2004-09-20T18:15:00+00:00/dc:date /item My sample of my PHP code is: ?php $library = simplexml_load_file('file.rss'); foreach ($library-item as $item) { echo $item-xpath('dc:date'); } ? I just want to get the date. Am I doing xpath incorrectly or does xpath not currently work properly in PHP5? -- --Matthew Sims --http://killermookie.org So I figured it out. ?php $library = simplexml_load_file('file.rss'); foreach ($library-item as $item) { list( ,$date) = each($item-xpath('dc:date')); echo $date; } ? -- --Matthew Sims --http://killermookie.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] simplexml and xpath
For this simple query simple do a call to $item-date to get your time. If the query is more complex in reality, do a foreach using xpath. See the example on Xpath at www.php.net/simplexml Yoed -Original Message- From: Matthew Sims [mailto:[EMAIL PROTECTED] Sent: Tuesday, September 21, 2004 1:42 PM To: [EMAIL PROTECTED] Subject: [PHP] simplexml and xpath So I've just recently fallen in love with simplexml. But from what I've read, is it true that xpath doesn't really work properly? I'm using an XML file that has a section like this: item titleTitle/title linkLink/link descriptionDesc/description dc:subjectSubject/dc:subject dc:date2004-09-20T18:15:00+00:00/dc:date /item My sample of my PHP code is: ?php $library = simplexml_load_file('file.rss'); foreach ($library-item as $item) { echo $item-xpath('dc:date'); } ? I just want to get the date. Am I doing xpath incorrectly or does xpath not currently work properly in PHP5? -- --Matthew Sims --http://killermookie.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML
Daniel Schierbeck wrote: I am having some problems with the XML features (I use the fancy new SimpleXML). It works like a dream when I'm retrieving information from an XML document, but when I want to insert new tags it screws up. I'm trying to create a function that saves error logs in an XML file, which should look like this: ?xml version='1.0' standalone='yes'? errors error number2/number stringCould not bla bla/string filefilename.php/file line56/line /error error number1/number stringFailed to bla bla/string filefilename2.php/file line123/line /error /errors I tried to use SimpleXML myself and had some strange behavior, so I ended up switching to DOM. I was already basically familiar with DOM anyway from javascript so development went quickly. You should take a look: http://www.php.net/dom There's more than one way to do it, of course, but code to add an element to this tree could look something like this: ?php // load the existing tree $doc = new DOMDocument(); $doc-load( errors.xml ); // count the number of existing error nodes $errors_node = $doc-documentElement; $error_count = $errors_node-getElementsByTagName( error )-length; // create the new error node... $error_node = $doc-createElement( error ); // ...and its children $number_node = $doc-createElement( number, $error_count + 1 ); $string_node = $doc-createElement( string, New error message ); $file_node = $doc-createElement( file, foo.php ); $line_node = $doc-createElement( line, 32 ); // add the children to the error node $error_node-appendChild( $number_node ); $error_node-appendChild( $string_node ); $error_node-appendChild( $file_node ); $error_node-appendChild( $line_node ); // add the new error node to the tree $doc-documentElement-appendChild( $error_node ); // save back to the file $doc-save( errors.xml ); ? -- Rick -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML
Rick Fletcher wrote: Daniel Schierbeck wrote: I am having some problems with the XML features (I use the fancy new SimpleXML). It works like a dream when I'm retrieving information from an XML document, but when I want to insert new tags it screws up. I'm trying to create a function that saves error logs in an XML file, which should look like this: ?xml version='1.0' standalone='yes'? errors error number2/number stringCould not bla bla/string filefilename.php/file line56/line /error error number1/number stringFailed to bla bla/string filefilename2.php/file line123/line /error /errors I tried to use SimpleXML myself and had some strange behavior, so I ended up switching to DOM. I was already basically familiar with DOM anyway from javascript so development went quickly. You should take a look: http://www.php.net/dom There's more than one way to do it, of course, but code to add an element to this tree could look something like this: ?php // load the existing tree $doc = new DOMDocument(); $doc-load( errors.xml ); // count the number of existing error nodes $errors_node = $doc-documentElement; $error_count = $errors_node-getElementsByTagName( error )-length; // create the new error node... $error_node = $doc-createElement( error ); // ...and its children $number_node = $doc-createElement( number, $error_count + 1 ); $string_node = $doc-createElement( string, New error message ); $file_node = $doc-createElement( file, foo.php ); $line_node = $doc-createElement( line, 32 ); // add the children to the error node $error_node-appendChild( $number_node ); $error_node-appendChild( $string_node ); $error_node-appendChild( $file_node ); $error_node-appendChild( $line_node ); // add the new error node to the tree $doc-documentElement-appendChild( $error_node ); // save back to the file $doc-save( errors.xml ); ? -- Rick Thanks, that looks promising! It would be slick if SimpleXML could handle that type of insertion, but i guess you can't get everything, eh? Best regards, Daniel -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] SimpleXML
From: Daniel Schierbeck [EMAIL PROTECTED] I am having some problems with the XML features (I use the fancy new SimpleXML). It works like a dream when I'm retrieving information from an XML document, but when I want to insert new tags it screws up. Someone will correct me if I'm wrong, but I don't think you can add elements to the XML file in this way. You can change existing values, but cannot add new elements from what I've seen. It seems pretty intuitive that it would work in the way you describe, so I don't know why it doesn't. ---John Holmes... UCCASS - PHP Survey System http://www.bigredspark.com/survey.html -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
RE: [PHP] SimpleXML node detection.
My peoblem is that i have something like the following xml... ~section ~namefoo/name ~contentfoo/content ~ignore / ~/section Any ideas on how i can check to see it the ignore node exists or not? You can't. This is a bug that just recently came to the developers attention, and is currently being discussed on the internals list. Cheers, Rick -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php