PHP - Simplexmlelement Attribute Parsing.
Similar Tutorialshi, im trying to parse this xml file : xml.gamebookers.com/sport /football.xml_attr.xml i want to echo on my page like this : league name 1 match 1 of league 1 odds odds odds match 2 of league 1 odds odds odds . . league name 2 match 1 of league 2 odds odds odds match2 of league 2 odds odds odds . . this is my code so far <?php $xml=simplexml_load_file('http://xml.gamebookers.com/sports/football.xml_attr.xml'); $league=$xml->xpath('//event/..'); // leagues refers to element<group> $matches=$xml->xpath('//bettype[@name="Versus (with Draw)"]/..'); // shows matches name (team versus team) $odds=$xml->xpath('//event/bettype[@name="Versus (with Draw)"]/bet'); //odds of matches 1 x 2 $leaguecount=count($league); $matchescount=count($matches); $oddscount=count($odds); $i=0; while ($i<$leaguecount){ echo $league[$i]['name'].'<br>'; $i++; } echo '<br><br>'; $i=0; while ($i<$matchescount){ echo $matches[$i]['name'].'<br>'; $i++; } $i=0; while ($i<$oddscount){ echo $odds[$i]['odd'].'<br>'; $i++; } ?> it prints this: http://www.mh724.com/school/xp.php so i need something like that: echo league[$i][mathces[$i][odds[$i] // like arrays of array but it does not work of course any help will highly appreciated :shrug: with regardS Hello! I am using CURL to access HTML and extract all the elements from it as below Code: [Select] ** * Initialize the cURL session */ $ch = curl_init(); /** * Set the URL of the page or file to download. */ curl_setopt($ch, CURLOPT_URL,'http://www.w3schools.com/PHP/php_xml_simplexml.asp'); /** * Ask cURL to return the contents in a variable * instead of simply echoing them to the browser. */ curl_setopt($ch, CURLOPT_FAILONERROR,1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT, 15); /** * Execute the cURL session */ $contents = curl_exec ($ch); /** * Close cURL session */ curl_close ($ch); This works perfectly , but my next step is to use SimpleXMLElement() and grab a particular element from it which is. Code: [Select] $xml_data = new SimpleXMLElement($contents); but I came across an article saying that there is no pint using SimpleXMLElement() to grab HTML Elements, Is that true? and BTW if I need to grab a particular element (in the already extracted HTML using CURL) what is the function I am supposed to use ? Thank you I have this SimpleXMLElement Object and I can't echo out any attribute. In this example I am only showing you one SimpleXMLElement Object of the entire result set just for brevity. Here is the code that loops through the results: foreach($oXML->links->link as $o){ echo "<pre>";print_r($o);echo "</pre>"; } SimpleXMLElement Object ( [advertiser-id] => 2860239 [advertiser-name] => Amber Alert GPS [category] => Array ( [0] => children [1] => children ) [click-commission] => Array ( [0] => 0.0 [1] => 0.0 ) [creative-height] => Array ( [0] => 0 [1] => 0 ) [creative-width] => Array ( [0] => 0 [1] => 0 ) [language] => en [lead-commission] => SimpleXMLElement Object ( ) [link-code-html] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [link-code-javascript] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [description] => 20% discount of Amber Alert GPS Child Locator Device when using "Amber2" Promo Code. [destination] => http://www.amberalertgps.com [link-id] => 10745524 [link-name] => "Hey Mom! Please Don't Lose Me Again." Use Promo Code "Amber2" To Get 20% Off New GPS Child Tracking Device! [link-type] => Text Link [performance-incentive] => false [promotion-end-date] => SimpleXMLElement Object ( ) [promotion-start-date] => SimpleXMLElement Object ( ) [promotion-type] => coupon [relationship-status] => joined [sale-commission] => 30.00% [seven-day-epc] => N/A [three-month-epc] => 2.66 ) I try to do this but it doesn't work: foreach($oXML->links->link as $o){ echo $o['advertiser-id']; } # I also tried this: foreach($oXML->links->link as $o){ echo $o->advertiser-id; } How do you echo the values? Hi Guys, I'm trying to run the following code but the page breaks with no errors. I'm using PHP 5 which should run Simple XML. Code seems fine to me... Code: [Select] <?php $xmlstr = "courses.xml"; $xml = new SimpleXMLElement($xmlstr); // I Know it's breaking at this line echo $xml->course[0]->name; ?> Hey Guys, I have a snippet of XML here.. Code: [Select] <courses> <course> <id>70</id> <name>Marketing and Social Media</name> <dates> <date> <instance_id>6747</instance_id> <location /> <course_type>Day</course_type> <date_available>2011/07/13</date_available> <time_start>9:30</time_start> <time_end>17:00</time_end> <availibility>7</availibility> <running_dates> <running_date>2011/07/13</running_date> <running_date>2011/07/14</running_date> </running_dates> </date> </dates> </course> I'm trying to run xpath query to return all the courses and running dates associated with it but I dont understand how I get the running_dates? This is what I have.. Code: [Select] <?php $xmlstr = "../wp-content/themes/iact/courses.xml"; $xml = new SimpleXMLElement($xmlstr, NULL, TRUE); foreach ($xml->xpath('//date/running_dates') as $date) { $t = "<p class='heading'>". $date->course_type."</p> <div class='content'>".$date->running_date."</div>"; // do I need to go into another foreach here to loop all of the running dates? hardly? echo $t; } ?> Hi guys, I'm constructing a PHP document, using SimpleXML- I want to set the encolding of the document to "ISO-8859-1" - how do I do this.. This prob is driving me nuts... Can someone please help? Thanks in advance. Will Hello, I'm in need of help. Sometimes my PHP reads XML from a ssh and it tends to fail at times. Heres my complete error: Code: [Select] [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: Entity: line 3: parser error : Premature end of data in tag info line 2 in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: ^ in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/nmdgamin/public_html/private/includes/functions/revision.php:69 Stack trace: #0 /home/nmdgamin/public_html/private/includes/functions/revision.php(69): SimpleXMLElement->__construct('<?xml version="...') #1 /home/nmdgamin/public_html/private/includes/functions/update.php(16): CheckRemoteRevision('SpaceBuild') #2 /home/nmdgamin/public_html/prv_updater.php(13): Update() #3 {main} thrown in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 Remote function: function CheckRemoteRevision($Name){ if($Name){ if($Query = MySQLQuery('SELECT name, url, sv_revision FROM data WHERE name=\''. $Name .'\';')){ if($XMLFile = shell_exec('svn info \''. $Query['url'] .'\' --username anonsvn --password anonsvn --xml')){ if($DCheck = explode(' ', $XMLFile)){ if($DCheck[0] == 'svn:'){ $Revision = '0'; $Result = MySQLQuery('UPDATE data SET sv_revision=\''. $Revision .'\' WHERE name=\''. $Query['name'] .'\';'); return False; } } $XML = new SimpleXMLElement($XMLFile); foreach($XML->entry as $Attribute){ $Revision = $Attribute['revision']; } if($Query['sv_revision'] < $Revision || $Query["sv_revision"] != $Revision){ $Result = MySQLQuery('UPDATE data SET sv_revision=\''. $Revision .'\' WHERE name=\''. $Query['name'] .'\';'); } return $Revision; }else{ return False; } }else{ return False; } }else{ return False; } } How would I full proof this from getting this error again, It seems to happen at completely random times. I'm not very good with XML in PHP Thanks! Hello, I have been working with PHP for many years, but have avoided XML parsing - now I know why. I am having some difficultly. In the following XML example, I am trying to read domain:name and domain:reason. I have struggled for the past 3 nights. Code: [Select] <?xml version="1.0" encoding="utf-8"?> <epp xmlns="urn:ietf:params:xml:ns:epp-1.0"> <response> <result code="1000"> <msg>Command completed successfully</msg> </result> <resData> <domain:chkData xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"> <domain:cd> <domain:name avail="0">foo.com</domain:name> <domain:reason>registered</domain:reason> </domain:cd> <domain:cd> <domain:name avail="0">foo.net</domain:name> <domain:reason>registered</domain:reason> </domain:cd> <domain:cd> <domain:name avail="0">foo.org</domain:name> <domain:reason>registered</domain:reason> </domain:cd> </domain:chkData> </resData> <trID> <svTRID>test-0000-0000</svTRID> </trID> </response> </epp> The code I am using is below. This assumes the above XML data is in a variable called $xmldata Code: [Select] $xml = new SimpleXMLElement($xmldata); foreach ($xml->response->resData as $entry){ $namespaces = $entry->getNameSpaces(true); $domain = $entry->children($namespaces['domain']); echo "Domain : " . $domain->name. "<br />"; echo "Domain : " . $domain->reason . "<br />"; } Can anyone advise where I am going wrong? Thanks in advance. I want to get the url in the [@attributes] Atm i get the title like this Code: [Select] foreach ($xmlTree->channel->item as $item) { echo '<p>'.$item->title.'</p>'; } i tried this Code: [Select] $imageUrl = $item->enclosure->@attributes->url; print_r2($imageUrl); but then i get this error: Quote Parse error: syntax error, unexpected '@', expecting T_STRING or T_VARIABLE or '{' or '$' in / this is the XML: Quote => SimpleXMLElement Object ( [title] => #3315: Woord van het jaar: weigerambtenaar, Arabische lente tweede, plaszak derde [link] => http://www.nrc.nl/nieuws/2011/11/26/woord-van-het-jaar-weigerambtenaar/?utm_campaign=rss&utm_source=syndication [pubDate] => Sat, 26 Nov 2011 17:00:55 +0100 [guid] => nieuws_153690 [description] => SimpleXMLElement Object ( ) [enclosure] => SimpleXMLElement Object ( [@attributes] => Array ( [url] => http://www.nrc.nl/wp-content/uploads/2011/11/vmBruidstaart5501_63103-586x4801-300x245.jpg [length] => [type] => image/jpeg ) ) ) <form action="jvs.php" method="post"> <input type="checkbox" name="box" value="haa"> <input type="submit" value="submit"> </form> <?php echo $_POST['name']; ?> hi all How can I get the value of name which is box through post or get from the code I have a parser.php file that presents me with a list of items inside an XML file differences.xml: <element> <item code="lM" name="castle" type="building"> <cost>5000</cost> </item> .....more items..... After selecting wanted items, the form submits to parsed.php. Now I want parsed.php to go back into the same XML file and insert only those selected items into a new array. parser.php code: <?php if (empty($option)){ $xml = simplexml_load_file('differences.xml'); $object = $xml->xpath('//item'); $count = count($object); $i = 0; echo "<form method='post' action='parsed.php'>"; while($i < $count){ $xmlname = $object[$i]['name']; echo "<input type='checkbox' name='option[".$i."]' value='$xmlname'>".$xmlname; echo "<br>"; $i++; } echo "<br><input type='submit' name='formSubmit' value='Proceed'><br>"; echo "</form>"; } ?> parsed.php code: <?php $option = $_POST['option']; if (isset($_POST['formSubmit'])) { if (!empty($option)){ $xml = simplexml_load_file('differences.xml'); $i = 0; $count = count($option); while($i < $count) { $object = $xml->xpath('//item[@name="$option[$i]"]'); echo $object[$i]['name']; echo "<br>"; $i++; } }else{ echo "No items selected, Please select:"; } } ?> The problem I am having is that echo $object[$i]['name']; is not returning any values (it is empty, I checked). The thing is though that $option[$i] does contain the selected value. I have narrowed my problem down to this part of my code: $object = $xml->xpath('//item[@name="$option[$i]"]'); echo $object[$i]['name']; Can someone help me narrow down my problem? I want to remove the current attribute of the tag and add the new one. I wrote the php program but it gives me no output. Can someone help me please??? Here is my code!!! <?php $xml = new DOMDocument(); $xml->load('test.xml'); $node = $xml->getElementsByTagName('*'); $nodename = ""; $node_name = ""; $att = ""; $attr_name = ""; $attr_value = ""; foreach($node as $value) { echo "Node Name is :".$value->nodeName; $nodename = $value->nodeName; $node_name = $xml->getElementsByTagName('$nodename')->item(0); echo $nodename; foreach($nod_name as $value1) { $att = $node_name->getAttributeNode('$value1'); echo "Node Name is :".$att->name; echo "<BR>Attribute Value is :".$att->value; $attr_name = $att->name; $attr_value = '"' . $att->value . '"'; $nodename->removeAttributeNode('$attr_name'); $nodename->setAttributeNode(new DOMAttr('$attr_name', '$attr_value')); } $xml->save('temp1.xml'); } ?>
I have researched the subject and found a few 'solutions' for my problem but cannot get it to work (I looked at ones in this forum). <?php //loop to collect and output db data as hyperlink with target="_blank" while($row = mysqli_fetch_assoc($result)) { //output data from each row echo "<a href='".$row[link]."'>♦ ".$row[title]."</a><br>"; } ?>
Hi All, Not sure if this is a silly question so here we go. I have some divs that have data attributes (data-value). When i submit and post the form, can i use these values as part of the submission and put their data-value into the db? Thanks as always in advance. Hello, I have made a PHP script that will feed an existing XML file. The file stores song details like, title, name of singer etc ... Now the file structure is like this for the moment: Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <music> <song> <title>Without me</title> <artist>Eminem</artist> <url>songs/coreIssues.mp3</url> <image>img/den.jpg</image> <discspeed>11</discspeed> </song></music> But I need it to be: Code: [Select] <?xml version="1.0" encoding="UTF-8"?> <music> <song mainTitle="Eminem - Without me"> <title>Without me</title> <artist>Eminem</artist> <url>songs/coreIssues.mp3</url> <image>img/den.jpg</image> <discspeed>11</discspeed> </song></music> I need it to be like that so if I want to delete a song from the list I just check for the element which will have a unique mainTitle and then delete that element with all it's details. Now, I've searched on Google for some solutions but didn't find any yet. Anyone here knows how to do this? Thanks! I am having trouble implementing PHP inside a HTML attribute. Every time I try to fix it, I seem to make things worse. Can someone please help me: <INPUT name="id" type="text" value=""<?php echo "$row['id']"; ?>""> How can this be written in PHP? Code: [Select] echo '<IMG alt="" src=".$row['id']/thumb.png">'; It has been brought to my attention that $_SERVER['PHP_SELF']; can be easily hacked. In this code... Code: [Select] <form id="login" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> Do I even need anything in the Action attribute if I am redirecting the form to itself?! Please advise... Debbie Hi Guys, New to php! I have a title attribute applied to a textarea but in the below code the title attribute just displays the first word of the associated sentence, if $translation is "The cat is on the mat" the title attribute on mouseover of the textarea only shows "The". Weird eh? Any ideas what the fix would be. Same in IE, Chrome and FF. How could I tweak this ".$translation." (highlighted in red in code below off to the right) in the context of the below code? It aint my code by the way By the way ".$translation." highlighted in green does show the full sentence eg "The cat is on the mat" I need the title attribute as a tooltip on a big matrix of textareas. Thanks Code: [Select] foreach ($translation_matrix[$this->ext->settings['base_language']] as $phrase_key => $translation) { $class = ($i % 2) ? "tableCellOne" : "tableCellTwo"; $r .= "<tr>"; $r .= "<td class='".$class." phrase-key'>".$phrase_key."</td>"; $r .= "<td class='".$class."'>[color=green]".$translation."[/color]</td>"; foreach ($matched_langs as $lang_key => $language) { $r .="<td class='".$class."'> ".$language."<textarea class='textarea' name='translations[".$lang_key."][".$phrase_key."]' title=[color=red]".$translation."[/color]>".((isset($translation_matrix[$lang_key][$phrase_key]) === TRUE) ? $translation_matrix[$lang_key][$phrase_key] : "")."</textarea></td>"; } $r .= "</tr>\n"; $i++; } $r .= "</tbody></table><input type='submit' value='".$LANG->line("submit")."' />"; $r .= "</form>"; $this->_render_layout('index', $r); } Hi, I have an XML Feed which is using ID's or Types. I need to select the specific node and convert it to a variable. Example XML Feed: Code: [Select] <tour> <tourName>Amazon Riverboat Adventure</tourName> <dossierCode>PVIIA</dossierCode> <tripDetails> <tripDetail type="StartFinish">ex Lima</tripDetail> <tripDetail type="What's Included">Lots of stuff </tripDetail> </tripDetails> I have been extracting this data by using: <?php if(!$xml=simplexml_load_file('xmlfeed.xml')){ trigger_error('Error reading XML file',E_USER_ERROR); } foreach ($xml->tourName as $tourname) foreach ($xml->dossierCode as $agentcode) ?> However I am unsure how I can extract the "ex lima" from StartFinish as $startfinish. Can anyone help? Many thanks! |