PHP - Problems Accessing Nodes After Using Simplexml_load_file
Hi!
I'm having trouble accessing data with simpleXML_load_file I have a working script that loads an XML-file and outputs in a proprietary format that I've written, but for some reason I can't get it to work with this second set of XML-files. Loading the file seems to work fine. I load the file into a variable, and can print the contents of the file using echo $xml -> asXML(); However, when I try to access a single node using: echo $xml->{'SOAP-ENV:Envelope'}->{'SOAP-ENV:Body'}->Order->OrderHeader->OrderNumber->BuyerOrderNumber;I get the following error: Notice: Trying to get property of non-object in C:\www\convert_uio.php on line 28 XML-file looks as follows: <?xml version="1.0" encoding="utf-8"?> <SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://www.w3.org/2003/05/soap-encoding" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <SOAP-ENV:Header> <nseps:endpoints SOAP-ENV:mustUnderstand="true" xmlns:nseps="urn:schemas-IBX:/docs/endpoint.nsendpoint"> <nseps:to> <nseps:address>8b51fc8c-7aba-1000-bbbe-c0a878330001</nseps:address> </nseps:to> <nseps:from> <nseps:address>1b0ad9d6-7a05-1000-a43c-c0a878330001</nseps:address> </nseps:from> </nseps:endpoints> <nsprop:properties SOAP-ENV:mustUnderstand="true" xmlns:nsprop="urn:schemas-IBX:/docs/property.nsproperty"> <nsprop:identity>fb1797dbb1f14a179482b1bb53bc7c14</nsprop:identity> <nsprop:sentAt>2014-09-02T00:00:00+01:00</nsprop:sentAt> <nsprop:topic>Order</nsprop:topic> </nsprop:properties> </SOAP-ENV:Header> <SOAP-ENV:Body> <Order xmlns="rrn:org.xcbl:schemas/xcbl/v3_5/xcbl35.xsd"> <OrderHeader> <OrderNumber> <BuyerOrderNumber>E14124673</BuyerOrderNumber> </OrderNumber> <OrderIssueDate>20140902T00:00:00+01:00</OrderIssueDate> <OrderReferences> <AccountCode> <Reference> <RefNum>no_unoslo</RefNum> </Reference> </AccountCode> </OrderReferences> <Purpose> <PurposeCoded>Original</PurposeCoded> </Purpose> <RequestedResponse> <RequestedResponseCoded>NoAcknowledgementNeeded</RequestedResponseCoded> </RequestedResponse> <OrderType> <OrderTypeCoded>PurchaseOrder</OrderTypeCoded> </OrderType> <OrderCurrency> <Currency> <CurrencyCoded>NOK</CurrencyCoded> </Currency> </OrderCurrency> <OrderLanguage> <Language LanguageDependent="false"> <LanguageCoded>no</LanguageCoded> </Language> </OrderLanguage> <OrderDates> <RequestedDeliverByDate>20140904T00:00:00+01:00</RequestedDeliverByDate> </OrderDates> <OrderParty> <BuyerParty> <Party> <PartyID> <Identifier> <Agency> <AgencyCoded>AssignedByBuyerOrBuyersAgent</AgencyCoded> </Agency> <Ident>no_uio</Ident> </Identifier> </PartyID> <NameAddress> <Name1>xxxxxxxxxxxxx</Name1> <Name2>xxxxxxxxxxxxx</Name2> <POBox>xxxxx</POBox> <PostalCode>NO-0316</PostalCode> <City>Oslo</City> <Country> <CountryCoded>NO</CountryCoded> </Country> </NameAddress> <OrderContact> <Contact> <ContactName>Some Name</ContactName> <ContactFunction> <ContactFunctionCoded>PurchasingContact</ContactFunctionCoded> </ContactFunction> <ListOfContactNumber> <ContactNumber> <ContactNumberValue>email@email.no</ContactNumberValue> <ContactNumberTypeCoded>EmailAddress</ContactNumberTypeCoded> </ContactNumber> <ContactNumber> <ContactNumberValue>+4700000000</ContactNumberValue> <ContactNumberTypeCoded>TelephoneNumber</ContactNumberTypeCoded> </ContactNumber> </ListOfContactNumber> </Contact> </OrderContact> </Party> </BuyerParty> <BuyerTaxInformation> <PartyTaxInformation> <TaxIdentifier> <Identifier> <Agency> <AgencyCoded>Other</AgencyCoded> <AgencyCodedOther>VAT Number</AgencyCodedOther> </Agency> <Ident>00000000</Ident> </Identifier> </TaxIdentifier> </PartyTaxInformation> </BuyerTaxInformation> <SellerParty> <Party> <PartyID> <Identifier> <Agency> <AgencyCoded>AssignedByBuyerOrBuyersAgent</AgencyCoded> </Agency> <Ident>8b51fc8c-7aba-1000-bbbe-c0a878330001</Ident> </Identifier> </PartyID> <NameAddress> <Name1>Name 2</Name1> <Street>Adress</Street> <PostalCode> 0314</PostalCode> <City>OSLO</City> <Country> <CountryCoded>NO</CountryCoded> </Country> </NameAddress> <OrderContact> <Contact> <ContactName>N/A</ContactName> <ListOfContactNumber> <ContactNumber> <ContactNumberValue>email</ContactNumberValue> <ContactNumberTypeCoded>EmailAddress</ContactNumberTypeCoded> </ContactNumber> <ContactNumber> <ContactNumberValue>47 0000000</ContactNumberValue> <ContactNumberTypeCoded>FaxNumber</ContactNumberTypeCoded> </ContactNumber> </ListOfContactNumber> </Contact> </OrderContact> </Party> </SellerParty> <ShipToParty> <Party> <PartyID> <Identifier> <Agency> <AgencyCoded>AssignedByBuyerOrBuyersAgent</AgencyCoded> </Agency> <Ident /> </Identifier> </PartyID> <NameAddress> <Name1>Name</Name1> <Name2>Name2 </Name2> <Street>Adress</Street> <StreetSupplement1>0318 Oslo</StreetSupplement1> <PostalCode>NO-0562</PostalCode> <City>OSLO</City> <Country> <CountryCoded>NO</CountryCoded> </Country> </NameAddress> <OrderContact> <Contact> <ContactName>Name</ContactName> <ContactFunction> <ContactFunctionCoded>PurchasingContact</ContactFunctionCoded> </ContactFunction> <ListOfContactNumber> <ContactNumber> <ContactNumberValue>emamil</ContactNumberValue> <ContactNumberTypeCoded>EmailAddress</ContactNumberTypeCoded> </ContactNumber> <ContactNumber> <ContactNumberValue>+470000000</ContactNumberValue> <ContactNumberTypeCoded>TelephoneNumber</ContactNumberTypeCoded> </ContactNumber> </ListOfContactNumber> </Contact> </OrderContact> <ReceivingContact> <Contact> <ContactName>Name</ContactName> <ContactFunction> <ContactFunctionCoded>PurchasingContact</ContactFunctionCoded> </ContactFunction> <ListOfContactNumber> <ContactNumber> <ContactNumberValue>email</ContactNumberValue> <ContactNumberTypeCoded>EmailAddress</ContactNumberTypeCoded> </ContactNumber> <ContactNumber> <ContactNumberValue>+4700000000</ContactNumberValue> <ContactNumberTypeCoded>TelephoneNumber</ContactNumberTypeCoded> </ContactNumber> </ListOfContactNumber> </Contact> </ReceivingContact> </Party> </ShipToParty> <BillToParty> <Party> <PartyID> <Identifier> <Agency> <AgencyCoded>AssignedByBuyerOrBuyersAgent</AgencyCoded> </Agency> <Ident>no_uio</Ident> </Identifier> </PartyID> <NameAddress> <Name1>Name</Name1> <Name2>Adress</Name2> <POBox>adress2</POBox> <PostalCode>NO-0316</PostalCode> <City>Oslo</City> <County /> <District>9908:971035854</District> <Country> <CountryCoded>NO</CountryCoded> </Country> </NameAddress> <OrderContact> <Contact> <ContactName>Name</ContactName> <ContactFunction> <ContactFunctionCoded>PurchasingContact</ContactFunctionCoded> </ContactFunction> <ListOfContactNumber> <ContactNumber> <ContactNumberValue>email</ContactNumberValue> <ContactNumberTypeCoded>EmailAddress</ContactNumberTypeCoded> </ContactNumber> <ContactNumber> <ContactNumberValue>+470000000</ContactNumberValue> <ContactNumberTypeCoded>TelephoneNumber</ContactNumberTypeCoded> </ContactNumber> </ListOfContactNumber> </Contact> </OrderContact> </Party> </BillToParty> </OrderParty> <OrderTermsOfDelivery> <TermsOfDelivery> <TermsOfDeliveryFunctionCoded>Other</TermsOfDeliveryFunctionCoded> <TermsOfDeliveryFunctionCodedOther>Other</TermsOfDeliveryFunctionCodedOther> <TransportTermsCoded>Other</TransportTermsCoded> <TransportTermsCodedOther>DDP</TransportTermsCodedOther> <ShipmentMethodOfPaymentCoded>Other</ShipmentMethodOfPaymentCoded> <ShipmentMethodOfPaymentCodedOther>Other</ShipmentMethodOfPaymentCodedOther> <TransportDescription /> </TermsOfDelivery> </OrderTermsOfDelivery> <OrderHeaderNote /> </OrderHeader> <OrderDetail> <ListOfItemDetail> <ItemDetail> <BaseItemDetail> <LineItemNum> <BuyerLineItemNum>1</BuyerLineItemNum> </LineItemNum> <LineItemType> <LineItemTypeCoded>Item</LineItemTypeCoded> </LineItemType> <ItemIdentifiers> <PartNumbers> <SellerPartNumber> <PartNum> <PartID>1000000000001</PartID> </PartNum> </SellerPartNumber> <ManufacturerPartNumber> <PartID /> </ManufacturerPartNumber> </PartNumbers> <ItemDescription>Normal frakt, pris 20 NOK</ItemDescription> </ItemIdentifiers> <TotalQuantity> <Quantity> <QuantityValue>1</QuantityValue> <UnitOfMeasurement> <UOMCoded>EA</UOMCoded> </UnitOfMeasurement> </Quantity> </TotalQuantity> <OffCatalogFlag>false</OffCatalogFlag> </BaseItemDetail> <PricingDetail> <ListOfPrice> <Price> <UnitPrice> <UnitPriceValue>20</UnitPriceValue> <Currency> <CurrencyCoded>NOK</CurrencyCoded> </Currency> <UnitOfMeasurement> <UOMCoded>EA</UOMCoded> </UnitOfMeasurement> </UnitPrice> <PriceBasisQuantity> <Quantity> <QuantityValue>1</QuantityValue> <UnitOfMeasurement> <UOMCoded>EA</UOMCoded> </UnitOfMeasurement> </Quantity> </PriceBasisQuantity> </Price> </ListOfPrice> <Tax> <TaxFunctionQualifierCoded>Tax</TaxFunctionQualifierCoded> <TaxCategoryCoded>StandardRate</TaxCategoryCoded> <TaxTypeCoded>ValueAddedTax</TaxTypeCoded> <TaxPercent>.00</TaxPercent> <TaxableAmount>20.00</TaxableAmount> <TaxAmount>.00</TaxAmount> </Tax> <TotalValue> <MonetaryValue> <MonetaryAmount>20.00</MonetaryAmount> </MonetaryValue> </TotalValue> </PricingDetail> <DeliveryDetail> <ListOfScheduleLine> <ScheduleLine> <Quantity> <QuantityValue>1</QuantityValue> <UnitOfMeasurement> <UOMCoded>EA</UOMCoded> </UnitOfMeasurement> </Quantity> <RequestedDeliveryDate>20140904T00:00:00+01:00</RequestedDeliveryDate> </ScheduleLine> </ListOfScheduleLine> </DeliveryDetail> </ItemDetail> <ItemDetail> <BaseItemDetail> <LineItemNum> <BuyerLineItemNum>2</BuyerLineItemNum> </LineItemNum> <LineItemType> <LineItemTypeCoded>Item</LineItemTypeCoded> </LineItemType> <ItemIdentifiers> <PartNumbers> <SellerPartNumber> <PartNum> <PartID>9788258312007</PartID> </PartNum> </SellerPartNumber> <ManufacturerPartNumber> <PartID /> </ManufacturerPartNumber> </PartNumbers> <ItemDescription>Hovedtariffavtalen i staten 1. mai 2014 - 30. april 2016 (p.100kr)</ItemDescription> </ItemIdentifiers> <TotalQuantity> <Quantity> <QuantityValue>2</QuantityValue> <UnitOfMeasurement> <UOMCoded>EA</UOMCoded> </UnitOfMeasurement> </Quantity> </TotalQuantity> <OffCatalogFlag>false</OffCatalogFlag> </BaseItemDetail> <PricingDetail> <ListOfPrice> <Price> <UnitPrice> <UnitPriceValue>100</UnitPriceValue> <Currency> <CurrencyCoded>NOK</CurrencyCoded> </Currency> <UnitOfMeasurement> <UOMCoded>EA</UOMCoded> </UnitOfMeasurement> </UnitPrice> <PriceBasisQuantity> <Quantity> <QuantityValue>1</QuantityValue> <UnitOfMeasurement> <UOMCoded>EA</UOMCoded> </UnitOfMeasurement> </Quantity> </PriceBasisQuantity> </Price> </ListOfPrice> <Tax> <TaxFunctionQualifierCoded>Tax</TaxFunctionQualifierCoded> <TaxCategoryCoded>StandardRate</TaxCategoryCoded> <TaxTypeCoded>ValueAddedTax</TaxTypeCoded> <TaxPercent>.00</TaxPercent> <TaxableAmount>100.00</TaxableAmount> <TaxAmount>.00</TaxAmount> </Tax> <TotalValue> <MonetaryValue> <MonetaryAmount>200.00</MonetaryAmount> </MonetaryValue> </TotalValue> </PricingDetail> <DeliveryDetail> <ListOfScheduleLine> <ScheduleLine> <Quantity> <QuantityValue>2</QuantityValue> <UnitOfMeasurement> <UOMCoded>EA</UOMCoded> </UnitOfMeasurement> </Quantity> <RequestedDeliveryDate>20140904T00:00:00+01:00</RequestedDeliveryDate> </ScheduleLine> </ListOfScheduleLine> </DeliveryDetail> </ItemDetail> </ListOfItemDetail> </OrderDetail> <OrderSummary> <NumberOfLines>2</NumberOfLines> <TotalTax> <MonetaryValue> <MonetaryAmount>.00</MonetaryAmount> </MonetaryValue> </TotalTax> <TotalAmount> <MonetaryValue> <MonetaryAmount>220.00</MonetaryAmount> <Currency> <CurrencyCoded>NOK</CurrencyCoded> </Currency> </MonetaryValue> </TotalAmount> </OrderSummary> </Order> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Similar TutorialsThis is a bit of a wierd problem, but I haven't been able to solve it so I thought I'd post it up here. Basically, I'm using the following function to access Maxmind's GEO IP database (so that I can target visitors to my site based on their location): <?php // This code demonstrates how to lookup the country by IP Address include("geoip.inc"); // Uncomment if querying against GeoIP/Lite City. // include("geoipcity.inc"); $gi = geoip_open("/home/bounce6/public_html/geoIP/GeoIP.dat",GEOIP_STANDARD); $ip=$_SERVER['REMOTE_ADDR']; $country=geoip_country_code_by_addr($gi, "$ip"); geoip_close($gi); ?> The function is being called using this line from a separate file: include "/home/username/public_html/mydomain.com/functions/getCountry.php"; Now the code does what it's supposed to do, in as far as it's able to give me a string which details where a visitor is located. However, for some strange reason it seems to be adding a new HTML tag into my existing header tag. The code which has been inserted is as follows: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> </head> <body> </body> </html> I've managed to isolate the problem to this script, so I know that there must be an issue with it, but I'm not quite sure what it is. Can anyone suggest why this extra source code is being produced? Is there a particular function that I'm using which is forcing additional headers or something?! Any thoughts would be really appreciated! My first stab at connecting to an API with php. The API takes a url and returns an xml file. When I try this: <?php $apicall = "https://www.graphicmail.com/api.aspx?Username=dyates@salemharvest.org&Password=x&Function=get_newsletters&SID=0"; $xml = simplexml_load_file($apicall); print_r($xml); ?> My local testing server responds with: Warning: simplexml_load_file() [function.simplexml-load-file]: Unable to find the wrapper "https" - did you forget to enable it when you configured PHP? However, in the php configuration file, php.ini, I have: 'allow_url_fopen = On' which is what the manual says is all you need for https use in most functions that take urls. The url that is $apicall works correctly when just pasted into the browser. When I try the php code on the production server I get no warning (they are turned off) and no output. Any ideas? Does the file have to be in the document root? If not, what is the correct syntax to point simplexml_load_file() to a directory on the server that is not the document root? ie what goes between the () this works fine if the .xml file is in my public html root - simplexml_load_file('sample.xml') but when I put the file in a different directory on the server, I can't figure out how to point to it. Help is appreciated. Hi.
I am trying to fetch xml from a betting website feed. The feed is restricted per IP but I have had the server IP, where the site is located, whitelisted and they have confirmed numerous times that the IP has definitely been whitelisted.
If I try to connect using simplexml_load_file to a BBC xml feed it works fine but to the betting feed I get "failed to open stream: HTTP request failed!"
Is there any way of knowing why it is failing or is there anything else that could prevent it from connecting to that specific feed?
many thanks in advance
Sam
first off I have to make an empty loc.xml file with permissions in order to write contents, I understand the permission idea. secondly, simplexml_load_file does nothing I get it straight from here http://us2.php.net/manual/en/function.simplexml-load-file.php <?php $request='http://z3950.loc.gov:7090/voyager?version=1.1&operation=searchRetrieve&query=dinosaur&startRecord=2&maximumRecords=5'; //echo $request; $filename = dirname(__FILE__)."/loc.xml"; $raw_xml = file_get_contents($request); //echo $raw_xml; $fp = fopen($filename, "w"); fwrite($fp, $raw_xml); fclose ($fp); // The file test.xml contains an XML document with a root element // and at least an element /[root]/title. if (file_exists($filename)) { $xml = simplexml_load_file($filename); print_r($xml); } else { exit('Failed to open loc.xml.'); } ?> I have an application that loads several xml files, and then outputs some of the data from the file. The problem is that every once in a while, the service that provides the xml file does maintenance (or has an error in the file), and my application gives a "Fatal error: Call to a member function children() on a non-object in..."
I would like to handle the error differently, by displaying "unavailable" instead of the error. I know that this is usually not the appropriate way of handling errors, because there is a reason for a fatal error.
Any ideas on how to appropriately handle this error?
// Node 217 (GGB) $xml = simplexml_load_file("http://services.my511.org/traffic/API_KEY_REMOVED_FOR_EXAMPLE"); foreach($xml->children() as $traveltime) { $ggb = "$traveltime->currentTravelTime"; } echo "GGB:" , $ggb , " Minutes"; Hi guys, This has been bothering me for quite some time. I have a piece of code that works absolutely fine on my local XAMPP setup but causes a 500 internal server error when I run it on my host (hostgator). $source = "marketplace_feed_v1.xml"; $xml = simplexml_load_file($source,'SimpleXMLElement', LIBXML_NOCDATA); SimpleXML is enabled on hostgator marketplace_feed_v1.xml is located in the same directory as this script I don't understand why this won't work Any help at all is much appreciated. I have a script that uses simplexml_load_file to download weather xml files. It works great except when the file doesn't exist. The server returns an HTML page when the xml file isn't available but the title is something.xml. How can I check to be sure it is an xml file and handle the error when it isn't. I have tried file_exists and access the return code (it's always 200). Can I access the doctype and determine if it HTML or XML? Hello fellow developers, Let me start by saying I'm still a PHP noob so please don't go too hard on me if I my code reflects this noobishness... So I'm trying to build a (very) simple RSS reader using jQuery and PHP. When the user clicks on an option from a dropdown, an AJAX call is made and passes the url selected from the list to a PHP script. The PHP script then loads the appropriate xml file from an 'xmlcache' folder. Everything is working just fine for files named as such: somefilename_1231231231.xml The problem is that I need it to be able to load files which have been urlencoded such as: http%3A%2F%2Ffeeds.feedburner.com%2Fajaxian_1235523548 In case you're wondering, the numbers at the end are a timestamp which will determine if the reader will load a cached copy of the desired xml file (if it's less than an hour old) or if it needs to get a fresh version (this part of the code is not written yet). Here is a look at my script thus far: <?php $url = "./xmlcache/" . urlencode($_REQUEST['url']); //access url from AJAX call echo $url; //outputs -> "./xmlcache/http%3A%2F%2Ffeeds.feedburner.com%2Fajaxian_1235523548.xml", which is the same as the file's name $curTime = time(); $urlParts = explode('_', $url); $urlTime = intval($urlParts[1]); $diff = $curTime - $urlTime; $urlAge = 60 * 60; //60sec * 60min = 3600sec or 1 hour if(file_exists($url)){ if($diff > $urlAge){ //the > will be switched to < to make logical sense once testing is done. $xml = simplexml_load_file($url); //ROOT TAG foreach($xml as $key0 => $value){ echo "$key0: $value"; foreach($value->attributes() as $attributeskey0 => $attributesvalue1){ echo "$attributeskey0: $attributesvalue1"; } echo "<br />"; //1 LEVEL BELOW ROOT TAG foreach($value as $key => $value2){ echo "$key: $value2"; foreach($value2->attributes() as $attributeskey => $attributesvalue2){ echo "$attributeskey = $attributesvalue2"; } echo '<br />'; //2 LEVELS BELOW ROOT TAG foreach($value2 as $key2 => $value3){ echo "$key2: $value3"; foreach($value3->attributes() as $attributeskey2 => $attributesvalue3){ echo "$attributeskey2 = $attributesvalue3"; } echo '<br />'; //3 LEVELS BELOW ROOT TAG foreach($value3 as $key3 => $value4){ echo "$key3: $value4"; foreach($value4->attributes() as $attributeskey3 => $attributesvalue4){ echo "$attributeskey3 = $attributesvalue4"; } echo '<br />'; //4 LEVELS BELOW ROOT TAG foreach($value4 as $key4 => $value5){ echo "$key4: $value5"; foreach($value5->attributes() as $attributeskey4 => $attributesvalue5){ echo "$attributeskey4 = $attributesvalue5"; } echo '<br />'; //5 LEVELS BELOW ROOT TAG foreach($value5 as $key5 => $value6){ echo "$key5: $value6"; foreach($value6->attributes() as $attributeskey5 => $attributesvalue6){ echo "$attributeskey5 = $attributesvalue6"; } echo '<br />'; } } } } echo '<br />'; } echo '<br />'; } }else{ //need to create the XML file from scratch, do a curl function, or read from a text file echo "need a new version"; //@unlink("$url); } }else{ echo "That file does not exist.<br/>"; } ?> The error message I'm getting is this: Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "./xmlcache/http%3A%2F%2Ffeeds.feedburner.com%2Fajaxian_1235523548.xml" in C:\wamp\www\reader\loadfeed.php on line 13 Warning: Invalid argument supplied for foreach() in C:\wamp\www\reader\loadfeed.php on line 16 The second error is obviously thrown because the file doesn't get loaded. I appreciate any help you gurus have to offer, and if you have any suggestions for the best way to load a fresh version that will be handled by the first else statement, I'm all ears. Thanks guys! Hi Guys! I'm new here at PHPFreaks, I have this problem using simplexml_load_file function. I am retrieving an XML from another sub-domain of my project, it's working fine on my local server (win xp, php 5.2.14) but when I try to execute it on our testing server (linux, php 5.2.14) it returns an error something like this.. Warning: simplexml_load_file([url of the script]) [function.simplexml-load-file]: failed to open stream: Connection timed out in [absolute path of the script] on line 3 i have tried cURL and file_get_contents, still get no luck. please note that the XML is validated via w3c.org and works really fine on my local server.. Thanks in advanced! I've been pulling my hair out for the past couple of hours working with simplexml_load_file(). I was attempting to consume a web service generated by asp.net that I've been consuming using CURL and a function to remove the BOM (byte order marker) so that I could load it into simplexml_load_string(). When I switched over to simplexml_load_file() to call the file instead of using CURL and my function, I was getting errors that it could not find the beginning '<' and that the document was empty and so on.. I couldn't find anything about simplexml_load_file() handling BOM characters, so I went for a walk. I came back to my desk and refreshed the page.. and it just started working. I changed nothing! Guess I should be happy that it started working, but I'd sure like to know why it was breaking in the first place, and then why it would suddenly start working without me doing anything. Has anyone else seen anything like this? Using HTML5 and CSS3, and jQuery is available.
I have a form block enclosing several hidden div blocks. jQuery will unhide a div block on selecting a control node -- presented as a tab.
I need to have a form input appear in more than one div block. That is, the HTML has four tabs, each tab making visible one of four div blocks. On one of the four div blocks, a specific form input is present.
I need for this specific input to also appear in one of the other div blocks. I want the one input, coded in one of the div blocks, to be "seen" and be operational in another div block -- but not have the HTML code for it located or duplicated there.
I thought about adding another input tag with the same name and showing the same value, but that is unworkable as it stands. I do not want to replicate or duplicate or otherwise make two separate inputs. But...
My current plan is to have two inputs of the same name, but the input in the hidden div block is disabled. By being disabled, the value of it will not be submitted. When the second div block becomes visible, the first input is disabled and the second is enabled. I would also need to copy the newly entered value into the other same-named input.
Could there be a better way?
Another way would be to move the specific input outside of the div blocks so that it is always visible. But I do not care to have this input visible for all the div blocks when each becomes visible.
Edited by bsmither, 08 January 2015 - 12:21 AM. Hello... I want to draw a nodes with arcs by using PHP. Is there any package available to do this? My nodes values are gene name. Please help me......... Hi all, i have a very large xml file containing 2000 child nodes. i am using DOMDocument to read xml data but it shows whole data at once, i want to fetch first 20 or 30 nodes first time and then rest leave for pagination. is there any way to do so. to read only first few records from xml file. Thanks in advance... Hi I have searched around for a solution to this and either fail to grasp how to get it to work or just cannot find the correct solution. I have the following XML file: Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <root> <product> <id>153</id> <images> <image id="1"> <url>http://www.mysite.com/product/images/1322.jpg</url> <title> <en>Book 1</en> </title> </image> <image id="2"> <url>http://www.mysite.com/product/images/1321.jpg</url> <title> <en>Book 2</en> </title> </image> <image id="3"> <url>http://www.mysite.com/product/images/1316.jpg</url> <title> <en>Book 3</en> </title> </images> </product> <product> <id>154</id> <images> <image id="1"> <url>http://www.mysite.com/product/images/1322.jpg</url> <title> <en>Book 1</en> </title> </image> <image id="2"> <url>http://www.mysite.com/product/images/1321.jpg</url> <title> <en>Book 2</en> </title> </image> <image id="3"> <url>http://www.mysite.com/product/images/1316.jpg</url> <title> <en>Book 3</en> </title> </images> </product> </root> $xml = 'example.xml'; // URL for feed. try{ $feed = new SimpleXMLElement($xml, null, true); }catch(Exception $e){ echo $e->getMessage(); exit; } $sql = 'INSERT INTO images (`id`, `url`) VALUES '; foreach($feed->property as $property){ $sql .= sprintf( "\n('%d', '%s'),", $property->id, mysql_real_escape_string($property->images->image->url) ); } $sql = rtrim($sql, ',') . ';'; What I need to do is loop through each of the image url nodes and insert them into my DB with the relevant id. Can somebody point me in the right direction with this please its driving me nuts! Regards GT good day dear phpfreaks.
I am new to PHP's SimpleXML. i want to work with SimpleXML on OSM-files. The original version of this question was derived from he OSM Data parsing to get the nodes with child https://stackoverflow.com/questions/16129184/osm-data-parsing-to-get-the-nodes-with-child
I am thankful that hakre offered a great example in the comments that makes a overwhelming goal: how to get more out of it: I want to filter the data to get the nodes with special category. Here is sample of the OSM data I want to get the whole schools within an area. The first script runs well - but now I want to refine the search and add more tags. Finally I want to store all into MySQL. So we need to make some XML parsing with PHP:
The following is a little OSM Overp
Quote
since i am learning - i break down the code into pieces...For my question, the second part is more interesting here. That is querying the XML data we have already. Again - as mentioned above: This is most easily done with xpath, the used PHP XML library is based on libxml which supports XPath 1.0 which covers the various querying needs very well. The following example lists all schools and tries to obtain their names as well.
# get all school nodes with xpath //node[tag[@k = "amenity" and @v = "school"]] This line says: Give me all node elements that have a tag element inside which has the k attribute value "amenity" and the v attribute value "school". Explanation: This is the condition we have to filter out those nodes that are tagged with amenity school. Further on xpath is used again - a second time: now relative to those school nodes to see if there is a name and if so to fetch it: Therefore we use the foreach-syntax:
foreach ($schools as $index => $school)
tag[@k = "name"]/@v'
tag[@k = "name"]/@v' Because not all school nodes have a name, a default string is provided for display purposes by adding it to the (then empty) result array:
list($name) = $school->xpath('tag[@k = "name"]/@v') + ['(unnamed)'];
Query returned 907 node(s) and took 1.10735 seconds. goal: to get out even more important data - see here Key:contact - OpenStreetMap Wiki
Well - we are already extracting the name: If we want to have more data then we just have to run a few more xpath queries inside our loop for all the address keys and the website. So - additionally: we do not have to forget to look for the website key additional to contact:website. cf: https://wiki.openstreetmap.org/wiki/Key:website conclusio: well - i think that i need to extend the xpath requests within the loop where xpath is used again, now relative to those school nodes to see if there is a name and if so to fetch it:
tag[@k = "name"]/@v' i did some further tess and found out very interesting things
$query = 'node
$context = stream_context_create(['http' => [
# please do not stress this service, this example is for demonstration purposes only.
$result = simplexml_load_file($endpoint);
//
# get all school nodes with xpath
$query = 'node
$context = stream_context_create(['http' => [
$endpoint = 'http://overpass-api.de/api/interpreter';
$result = simplexml_load_file($endpoint);
me/martin/dev/php/o1.php on line 68
33 School(s) found:
so far so good : if i add some lines in the part 2 i run into errors... -see below: i want to get more data out of it: - and coded like so;
{ note - within the part 2 that works with the XML-Result.
//
# get all school nodes with xpath
contact:phone I will dig into all documents and come back later the weekend... and report all the findings well - i think that i need to extend the xpath requests within the loop where xpath is used again, now relative to those school nodes to see if there is a name and if so to fetch it:
tag[@k = "name"]/@v'
more infos Hi guys, I'm using PHP Simple DOM, thanks to the good folk her I'm making progress. The html i'm parsing has a bunch of links in a li ul structure. I've managed to get the top layer of links extracted and I would like to have a count of the number of child nodes in the layer below the main links. Here is my code: $html = file_get_html('test/php/book.html'); if(!empty($html)){ $lis = $html->find('.chunklist', 0)->children() ; for ( $i = 0 ; $i < count($lis) ; $i++ ) { $parent_term = $lis[$i]->first_child()->innertext . ', ' ; $parent_node = $lis[$i]->children[0]->attr['href'] . '<br>' ; //echo count($parent_node->children()) ; this gives error Warning: count(): Parameter must be an array or an object that implements Countable echo $parent_term . $parent_node ; $parent_node = $const . $parent_node ; echo $parent_node ; $html2 = file_get_html($parent_node) ; $lis2 = $html2->find('.chunklist', 0)->children() ; } } I don't see anything in the manual regarding counting nodes, any idea how to go about this? Hi, I need to build my own xml validator and was wondering, what are some possible purposes of having multiple text nodes for a given parent node, I ask b/c while I was playing around with W3schools XML validator, I noticed it successfully validated the following: <?xml version="1.0" encoding="utf-8" ?> <note> <to>Joh</to> <from>Frank</from> <body>Hello world</body> Extra text node that is validated! </note> good day dear experts,
<?php /** * OSM Overpass API with PHP SimpleXML / XPath * * PHP Version: 5.4 - Can be back-ported to 5.3 by using 5.3 Array-Syntax (not PHP 5.4's square brackets) */ // // 1.) Something is wrong an OSM Overpass API Endpoint // $Something is wrong = 'node ["addr:postcode"~"RM12"] (51.5557914,0.2118915,51.5673083,0.2369398)->.point; ( node (around.point:100000) ["amenity"~"school"]; way (around.point:100000) ["amenity"~"school"]; ); out;'; $context = stream_context_create(['http' => [ 'method' => 'POST', 'header' => ['Content-Type: application/x-www-form-urlencoded'], 'content' => 'data=' . urlencode($Something is wrong), ]]); # please do not stress this service, this example is for demonstration purposes only. $endpoint = 'http://overpass-api.de/api/interpreter'; libxml_set_streams_context($context); $start = microtime(true); $result = simplexml_load_file($endpoint); printf("Something is wrong returned %2\$d node(s) and took %1\$.5f seconds.\n\n", microtime(true) - $start, count($result->node)); // // 2.) Work with the XML Result // # get all school nodes with xpath $xpath = '//node[tag[@k = "amenity" and @v = "school"]]'; $schools = $result->xpath($xpath); printf("%d School(s) found:\n", count($schools)); foreach ($schools as $index => $school) { # Get the name of the school (if any), again with xpath list($name) = $school->xpath('tag[@k = "name"]/@v') + ['(unnamed)']; printf("#%02d: ID:%' -10s [%s,%s] %s\n", $index, $school['id'], $school['lat'], $school['lon'], $name); }
FATAL ERROR syntax error, unexpected 'is' (T_STRING) on line number 11
well at the moment i try to make up my mind what is going on here So here's what I'm trying to do, and I haven't found any clear tutorials on how to properly navigate a DOMDocument object, at least not in the strict sense of PHP. I'm building a web scraper, I've had it working for some time now using more traditional methods (a combination of string manipulation and clever regex). I've been told xpath can be much faster and more reliable for what I need. Sold. Let's say I'm parsing a forum. This forum separates each reply in a post with a set of <li></li> with a class of "message" Code: [Select] <li class="message"> // Stuff here </li> <li class="message"> // Stuff here </li> So far so good. These list items contain all the formatting for each post, including user info and the message text. Each sitting in it's own div. Code: [Select] <li class="message"> <div class="user info"> User info here </div> <div class="message text"> Message text here </div> </li> <li class="message"> <div class="user info"> User info here </div> <div class="message text"> Message text here </div> </li> Still with me? Good. With this bit of code I can select each message list item block and iterate over all the sub nodes inside. Code: [Select] $items = $xpath->query("//li[starts-with(@class, 'message')]"); for ($i = 0; $i < $items->length; $i++) { echo $items->item($i)->nodeValue . "\n"; } This produces a basic text dump of the entire forum. Close, but not what I need. What I'm trying to do is as follows Select all the class="message" list items [done] Once those have been selected, run another $xpath->query to select the child nodes which contain the user info and message text Step one is done, step two is what is confusing me. How can I run a new query based on the output from the first query? Thanks guys |