PHP - Simple Xml: Delete Node By Id
XML file:
<?xml version="1.0" ... >
<database xmlns:xsi="http://www.w3.org/20...hema-instance"> <record> <id>1</id> <name></name> </record> <record> ... </record> </database> I want to delete the record where <id> equals $_GET['id']. I tried many suggested implementations based on xml or simplexml, without result. Came across a very simple workaround (it should omit the record where id=$id), but can someone help me to taylor it to my xml scheme? <?php $file = "database.xml"; $id = $_GET['id']; echo "DELETING: ".$id; $xml = simplexml_load_file($file); $str = "<?xml version=\"1.0\"?> <database>"; foreach($xml->children() as $child){ if($child->getName() == "id") { if($id == $child['name']) { continue; } else { $str = $str.$child->asXML(); } } } $str = $str." </database>"; echo $str; $xml->asXML("database_backup.xml"); $fh = fopen($file, 'w') or die("can't open file"); fwrite($fh, $str); fclose($fh); ?> Similar TutorialsHi All, I have a simple 'delete record' code that is not working. Would someone please take a gander at it and let me know if they see anything wrong that would prevent it from actually deleting a record. Code: [Select] <?php //connects to the database include ('db_connect.php'); //post variable $pk = $_POST['pk']; //MySQL code to query ---- 'contacts' = table & 'primary_key' = record id # $deleteContact = "DELETE FROM `contacts` WHERE `primary_key` = ".$pk." LIMIT 1"; //excutes query to MySQL $res = mysqli_query($link,$deleteContact); //close connection to database mysqli_close($link); ?> Any help would be great. Thank you. Hello, I am a new user here and new in php coding also. I am a student and i have this task to create a simple website and I am stacked at the Amend and Delete data, so i could really use any help asap. I really need your help because i have to finish this now. I have this search.php that searches my users and displays the user-names and next to them an Amend and a Delete button the links are like this: echo "<a href=:\"amend.php?id=" . $a_row['username'] . "\">Amend user</a>"; echo "<span> </span>"; echo "<a href=:\"delete.php?id=" .$a_row['username'] . "\">Delete user</a>" what code should i have in amend.php to make this work? Thanks in advance I have a form that submits a record and saves it to the database, I've got that working already, I'm trying to figure out if there is a cleaner way to delete a record with a button that gets a value from the unique key, in this case 'id' here is how the delete button looks like: // get info from table $query = "SELECT id, Title, Message FROM table_name"; $result = mysql_query($query); //displaying all data while($row = mysql_fetch_assoc($result)) { echo" <div class='status'><h3>{$row['Title']} <br></h3>" . " <h5>{$row['Message']} <br><br></h5>"; $id = $row['id']; //trying to get unique key from database //delete button echo "</div> <form action='delete.php' method='post' /> <input type='hidden' name='delete' value='yes' /> <input type='hidden' name='id' value='$id' /> <input type='submit' value='remove' /></form>"; } As you can see, i'm trying to give $id a unique value but for some reason i'm not getting it. The delete.php code looks like this: if (isset($_POST['delete']))// check if delete was clicked { $query = "DELETE FROM table_name WHERE id='$id'"; echo "$id Deleted successfully"; } elseif(!mysql_query($query, $db_server)) { echo "DELETE failed: $query<br />" . myql_error() . "<br /><br />"; } mysql_close(); I'm new to php and still learning so, if you think there are other ways to do this, please let me know, the button won't do anything to the data. Thanks in advance I'd like to write - or acquire - code that displays a simple table (name, phone number, email address, plus a comments field) on a web page in a password-protected page and allows a user to add his own information, update it or delete it. I figure hundreds of people and companies have written something like this so I'd like to find either an example I can imitate or even an existing package that I can simply customize to the specifics for my own table. Can anyone help me with that? Or am I going to have to reinvent the wheel for the gazillionth time and write it myself? Hi all. Here is my scripts which allow user to check multiple rows of data and delete it , but it require select data and click for twice to delete the rows , what should be the error? Code: [Select] <form name="frmSearch" method="post" action="insert-add.php"> <table width="600" border="1"> <tr> <th width="50"> <div align="center">#</div></th> <th width="91"> <div align="center">ID </div></th> <th width="198"> <div align="center">First Name </div></th> <th width="198"> <div align="center">Last Name </div></th> <th width="250"> <div align="center">Mobile Company </div></th> <th width="100"> <div align="center">Cell </div></th> <th width="100"> <div align="center">Workphone </div></th> <th width="100"> <div align="center">Group </div></th> </tr> </form> <? echo "<form name='form1' method='post' action=''>"; while($objResult = mysql_fetch_array($objQuery)) { echo "<tr>"; echo "<td align='center'><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=\"$objResult[addedrec_ID]\"></td>"; echo "<td>$objResult[addedrec_ID] </td>"; echo "<td>$objResult[FirstName]</td>"; echo "<td>$objResult[LastName] </td>"; echo "<td>$objResult[MobileCompany] </td>"; echo "<td>$objResult[Cell] </td>"; echo "<td>$objResult[WorkPhone] </td>"; echo "<td>$objResult[Custgroup] </td>"; echo "</tr>"; } echo "<td colspan='7' align='center'><input name=\"delete\" type=\"submit\" id=\"delete\" value=\"Delete\">"; if (isset($_POST['delete']) && isset($_POST['checkbox'])) // from button name="delete" { $checkbox = ($_POST['checkbox']); //from name="checkbox[]" $countCheck = count($_POST['checkbox']); for($d=0;$d<$countCheck;$d++) { $del_id = $checkbox[$d]; $sql = "DELETE from UserAddedRecord where addedrec_ID = $del_id"; $result2=mysql_query($sql) or trigger_error(mysql_error());;; } if($result2) { $fgmembersite->GetSelfScript(); } else { echo "Error: ".mysql_error(); } } echo "</form>"; Thanks for every reply. <body> <?php include 'sql.php'; $query = "SELECT * FROM validation"; $result = mysqli_query($con , $query); $rows = mysqli_fetch_assoc($result) ; $totals = mysqli_num_rows($result) ; ?> <div id="css"> <form > <table width="80%" border="0" cellpadding="2" cellspacing="2" > <caption><h2>Personal Details of Customers</h2></caption> <tr class="white"> <td bgcolor="#330033"> </td> <td bgcolor="#330033"> Id Number </td> <td bgcolor="#330033"> Full Name </td> <td bgcolor="#330033"> Email Address </td> <td bgcolor="#330033"> Website </td> <td bgcolor="#330033"> Comment </td> <td bgcolor="#330033"> Time </td> </tr> <?php while($rows=mysqli_fetch_assoc($result) { <tr> <input type="raido" name="ID" value="<?php echo $rows['ID']; ?>" /> <td bgcolor="#FFFFCC"><?php echo $rows['ID'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Name'];?> </td> <td bgcolor="#FFFFCC"><?php echo $rows['Email'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Website'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Comment'];?></td> <td bgcolor="#FFFFCC"><?php echo $rows['Time'];?></td> <td> </td> <td> <a href="delete.php? ID= "$rows[ID]" /"> <input type="submit" name="del" value="Delete" /> </a> <input type="button" name= "edit" value="Edit" /> </td> </tr> }?> </table> </form> </div> </body> Hi,
I wish to find out is there any possible that I can delete some data inside my php website but inside my sql database, the record will still at there?
Thank you.
Hello I have xml like this. <?xml version="1.0" encoding="utf-8"?> <data> <item ID="30001"> <Company>Navarro Corp.</Company> </item> <item ID="30002"> <Company>Performant Systems</Company> </item> <item ID="30003"> <Company>Digital Showcase</Company> </item> </data> All i need to do is get any one of the whole node from starting item tag to ending item tag from the xml, for example. getting <item ID="30002"> <Company>Performant Systems</Company> </item> from whole xml file. Can this be achieved using SimpleXML object from PHP? if not how it can be done. Thanks in advance watsmyname How do I update an xml node? Currently I have this: $xml = simplexml_load_file($xmlfile); $user = $xml->xpath('/root/users/user/name'); $usr = $user[0][0]->asXML(); $usr = $name; I don't know if that I right or not, but I do know that if it is right, it isn't updating the xml file. Am I on the right track, or not? What can I do? I'm trying to add/update an xml like so: $xml->Header->Record->$curblk->$row = $value; where $curblk and $row are obviously nodes. Problem is that sometimes I need to add/update nodes of the same name so I tried this: $xml->Header->Record->$curblk->$row[$multi] = $value; where $multi would represent the number (or instance or key?) of that node I wish to add/update. Issue with that is, php thinks that I'm tring to set the node as an array, which is not possible! So how do I dynamically add/update $row[0] , $row[1] , $row[2] base on the two variable, $row and $multi? ie: $row = Jim Bob; $multi = 0; <author>Jim Bob</author> $row = Tom Reed; $multi = 1; <author>Tom Reed</author> You get: <book> <author>Jim Bob</author> <author>Tom Reed</author> </book>Of course there is muuuuch more to it than that, but that is about as simple as I can explain it... Of course thank you for any help, i've been stuck on this for 3 days now! and my boss is not happy, especially since I'm a vary novice developer that took on this assignment... Can someone please explain to me what's the importance of node order? Does certain nodes that appear first or last have impact on traversing time? Any suggestions much appreciated! I'm trying to delete the <identifier> node of some XML, using the following code; unsuccessfully.
Can someone help me identify where I'm going wrong? TIA
$newXML = ""; $xmlString = Fedora_API::callGetDatastreamContents($this->pid, 'MODS', true); $doc = DOMDocument::loadXML($xmlString); $xpath = new DOMXPath($doc); $fieldNodeList = $xpath->query("/identifier"); foreach ($fieldNodeList as $node) { $fieldNodeList->removeChild($node); } $newXML = $doc->SaveXML(); I'm trying to set it so that it will delete an entire populated directory based upon a value in the database then after finishing that to go back and delete that row in the database. my current code is Code: [Select] <?php $page_title = "Central Valley LLC | Photo Addition" ?> <?php include("header.php"); ?> <?php include("nav.html"); ?> <div id="content"> <form action="delprod.php" method="post" enctype="multipart/form-data"> <label for="which">Choose A Product To Remove:</label> <?php $con = mysql_connect("localhost","phoenixi_cv","centraladmin"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("phoenixi_cvproducts", $con); $result = mysql_query("SELECT * FROM Products"); echo "<select name=\"which\">"; while($row = mysql_fetch_array($result)) { echo "<option "; echo "value=\"" . $row['id'] . "\">"; echo $row['Name'] . "</option>"; } echo "</select>"; mysql_close($con); ?> <br /> <input type="submit" name="submit" value="Submit" /> </form> </div><!--#content--> <?php include("footer.html") ?> and the delete script Code: [Select] <?php $con = mysql_connect("localhost","phoenixi_cv","centraladmin"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("phoenixi_cvproducts", $con); $result = mysql_query("SELECT id FROM Products WHERE id=$_POST['which']"); $row = mysql_fetch_array($result) chdir('assets'); chdir('images'); $mydir = $row . '/'; $d = dir($mydir); while($entry = $d->read()) { if($entry!="." && $entry!="..") { unlink($_POST['which'] . '/' . $entry); } } rmdir($mydir); $result = mysql_query("DELETE * FROM Producs WHERE id=$_POST['which']"); ?> Thank you in advance for all your help. any easier ways of approaching this will be welcome as well Hi All, I've been struggling to get the following code to work. I have an API feed that looks like this:
<Jobs> <Job> <ID>1805</ID> <Name>House Additions/Alterations </Name> <Description>House</Description> <Client> <ID>16178470</ID> <Name>client name 1</Name> </Client> <ClientOrderNumber></ClientOrderNumber> <State>In Construction</State> <StartDate>2018-03-26T00:00:00</StartDate> <DueDate>2020-03-31T00:00:00</DueDate> <Contact> <ID>10195532</ID> <Name>Clent Name1</Name> </Contact> <InternalID>25026686</InternalID> <Manager> <ID>610781</ID> <Name>Manager Name 1</Name> </Manager> <Partner> <ID>610781</ID> <Name>patner name</Name> </Partner> <Assigned> <Staff> <ID>610781</ID> <Name>Staff 1</Name> </Staff> ......... I'm trying to work out how to show all the job ID, Job Name, Client Name, Start Date etc that are specific to the assigned staff member by selecting a specific staff member. $Staff is populated by a dropdown earlier in the code. here's my code so far: if ($err) { echo "cURL Error #:" . $err; } else { $xml=simplexml_load_string($response) or die("Error: Cannot create object"); $jobs = $xml->xpath("Jobs/Job/Assigned/Staff[Name= '$Staff']"); foreach($jobs as $item) { //foreach($xml->Jobs->Job as $item) { $item1 = $item->Client->Name; $job_no = "$item->ID"; $job_name = "$item->Name"; $job_client = "$item1"; $job_start = "$item->StartDate"; $job_due = "$item->DueDate"; $job_status = "$item->State"; echo "<tr><td>$job_no</td><td><a href='activecp/managejob.php?job_id=$job_no'>$job_name</a></td><td>$job_client</td><td>$job_status</td><td>$job_start</td><td>$job_due</td></tr>"; } } This currently shows the ID and name of the selected staff member but not the info i need. All of the data I want to show is before the Assigned/Staff . Any help would be much appreciated. Thanks in advance. Hi, I have a RSS feed cached as an XML file. I need to pull some info out of it so I can then print it to the page. Currently I am using this code to extract the data: $doc = new DOMDocument(); $doc->load('inthenews.xml'); $inthenews = array(); foreach ($doc->getElementsByTagName('item') as $node) { $itemRSS = array ( 'title' => $node->getElementsByTagName('title')->item(0)->nodeValue, 'link' => $node->getElementsByTagName('link')->item(0)->nodeValue, 'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue, ); array_push($inthenews, $itemRSS); } However, the Description node contains more than I want. I need to remove everything except for the image ( <img../> ) it contains. Is there some way of running preg or similar on the nodeValue as it is extracted? Or an alternative to "getElementsByTagName" that allows searching for strings? If not, does anyone have a suggestion for doing this? I tried running preg_replace on the array, but it doesn't seem to do anything?? An example of the Array created by my code above is shown below: Code: [Select] [0] => Array ( [title] => BBC radio Cambridge 7.20am [link] => images/news/Matthew_Freeman_Radio_Cambridgeshire_21-10-10.mp3 [desc] => <img alt="BBC-logo" src="http://www2.mrc-lmb.cam.ac.uk/images/news/BBC-logo.jpg" height="54" width="127" /><br/>BBC radio Cambridge 7.20am 21.10.10: Dr Matthew Freeman"<br/> 21 October 2010 ) Thanks in advance for any advice Phil I would like to adding a node to a tree. I want it to be a balanced b-tree. The logic/algorithm i can think of is Code: [Select] <?php function add_node($root, $node) // Where $root is the parent to which node should be added and $node is the node that is to be added. { Traverse the tree level wise, level 1 being the lchild and rchild of $root and calculate the number of node in that level if(number of nodes in a level < 2[sup]$level[/sup]) // Since number of nodes a level can accommodate = 2[sup]$level[/sup] { Add node in that level where ever it gets an empty spot. } } ?> Tree table:- Code: [Select] CREATE TABLE IF NOT EXISTS `tree` ( `parent` int(7) NOT NULL, `rchild` int(7) NOT NULL, `lchild` int(7) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; Is their any better logic to do so ? Hi, I am new to xml parsing and I just want to know how to check whether a node has attributes: Here is my xml file to use: ================= Code: [Select] <?xml version="1.0" encoding="ISO-8859-1"?> <email> <message> <to> <toFirstName>Tove</toFirstName> <toLastName toType="common" style="swag">Smith</toLastName> </to> <from> <fromFirstName>Jani</fromFirstName> <fromLastName fromType="unique">Dravison</fromLastName> </from> <heading>Reminder</heading> <body> <prologue>Tis the night before Xmas...</prologue> <paragraph1>Don't forget me this weekend!</paragraph1> <paragraph2>Jump the gun!</paragraph2> <epilogue>The end of the world.</epilogue> </body> </message> <message> <to>employees</to> <from>CEO</from> <heading>Power Lunch</heading> <body> <prologue></prologue> <paragraph1>Year over year data</paragraph1> <paragraph2>Downsizing</paragraph2> <epilogue>The end.</epilogue> </body> </message> </email> Here the simple script that I cannot get to work: ================================== Code: [Select] <?php $simpleXMLObj=simplexml_load_file("email.xml"); if($simpleXMLObj->to[0]->toLastName[0]->attributes()->getName) print "YES: this node has attributes!"; else print "NO:"; ?> Please I really need help, it is simple I know but I am new to xml parsing and mixed up. I am creating a football predictor game and have a table in the database to hod all my users i have written a query to pull all out the users that have made a prediction that day with their predictions made i have put this into an array so my array will hold all the user details 1 being their userId I have set the order by on the query to userId so I get all the same users predictions in 1 block. I now want to extract all the predictions for each user and put these into their own array but I don't know which users the array will hold, how many users their will be, or how many predictions each user would have made so i'm not sure how to create this array i'm quite new to php can anyone help me with this How can I print the attributes of a child node? I have been trying and looking and cant get it. I need the attributes of subfield printed after datafield so a line would look like datafield plus attributes plus subfield attributes plus subfield =906 __$a0$bcbc$corignew etc... <?php //child nodes http://www.w3schools.com/php/php_xml_dom.asp //http://books.google.com/books?id=ygQRKDEsLecC&pg=PA196&lpg=PA196&dq=print+php+xml+child+node+attributes&source=bl&ots=TCAhH4kpCt&sig=yJUPXesIkRUrNXdNE9Yr5ul7Wdw&hl=en&ei=U51kTeKQKsL48AbN4MDTBg&sa=X&oi=book_result&ct=result&resnum=10&ved=0CF4Q6AEwCQ#v=onepage&q=print%20php%20xml%20child%20node%20attributes&f=false //http://stackoverflow.com/questions/4598409/printing-content-of-a-xml-file-using-xml-dom $doc = new DOMDocument(); $doc->preserveWhiteSpace = FALSE; $doc->load( 'loc.xml' ); $root = $doc->documentElement; $type = $root->nodeType; //print $doc->nodeName."\n"; //print $root->nodeName."\n"; //print $doc->nodeValue."\n"; //print $root->nodeValue."\n"; $librecords = $doc->getElementsByTagName( "record" ); foreach( $librecords as $record ){ $leader = $record->getElementsByTagName( "leader" ); $controlfields = $record->getElementsByTagName( "controlfield" ); $datafields = $record->getElementsByTagName( "datafield" ); $subfields = $record->getElementsByTagName( "subfield" ); $leader = $leader->item(0)->nodeValue; echo '=LDR '.$leader.'<BR>'; foreach( $controlfields as $controlfield ){ $tag = $controlfield->getAttribute('tag'); $cf_value = $controlfield->firstChild->nodeValue; echo "=".$tag." ".$cf_value.'<BR>'; } foreach( $datafields as $datafield ){ $tag = $datafield->getAttribute('tag'); $ind1 = $datafield->getAttribute('ind1'); $ind2 = $datafield->getAttribute('ind2'); if ($ind1 ==" ") {$ind1 = "_";} if ($ind2 ==" ") {$ind2 = "_";} echo "=".$tag." ".$ind1.$ind2; //if($datafield->hasChildNodes()){echo 'This node has children!<br />';} foreach ($datafield->childNodes AS $item) { // $arr = $item->attributes; print $arr; print 'nodeName '.$item->nodeName . " = " . $item->nodeValue." | " ;} //. "<br />"; } // foreach ($datafield->children() as $node) { // $arr = $node->attributes(); // returns an array // print ("code=".$arr["code"]); // get the value of this attribute // print (" Company=".$node->subfield); // print ("<p><hr>"); //} // foreach( $subfields as $subfield){ // foreach($subfield->attributes as $attr){ // $attributes = $subfield->attributes; // print $attr->nodeName; // print $attr->nodeValue; // //print $attributes->nodeName; //print $attributes->nodeValue; // print $subfield->nodeName; // print $subfield->nodeValue; //}} // print $item->nodeValue ; // print $item->attributes("code"); // $valueID = $item->getAttribute('code'); // print $item->nodeName->attributes("code"); // echo $item->nodeValue.getAttribute("code"); // print $item->getAttribute('code') //http://www.devshed.com/c/a/PHP/Accessing-Attributes-and-Cloning-Nodes-with-the-DOM-XML-Extension-in-PHP-5/1/ echo '<BR>'; } foreach( $subfields as $subfield ){ $code = $subfield->getAttribute('code'); $sf_value = $subfield->firstChild->nodeValue; echo '$'.$code.$sf_value.'<BR>'; } echo '<BR>'; } ?> Code: [Select] <leader>01026ngm a22002773a 4500</leader> <controlfield tag="001">16429180</controlfield> <controlfield tag="005">20100823131409.0</controlfield> <controlfield tag="007">vffcjaho|</controlfield> <controlfield tag="008">100823s2010 xxu060 mleng </controlfield> <datafield tag="906" ind1=" " ind2=" "> <subfield code="a">0</subfield> <subfield code="b">cbc</subfield> <subfield code="c">orignew</subfield> <subfield code="d">u</subfield> <subfield code="e">ncip</subfield> <subfield code="f">20</subfield> <subfield code="g">y-movingim</subfield> </datafield> <datafield tag="955" ind1=" " ind2=" "> <subfield code="b">qm12 2010-08-23</subfield> </datafield> I am trying to use php to loop through an xml file and reorganize the data. For example, if I have a xml file about books and the first xml sub tag under the <book> tag is "<type>" . I would like to make the following tags (nodes?) as child nodes under the type tag. For example, instead of this: Code: [Select] <book> <type>nonFiction</type> <title>Advanced PHP Programming</title> <author>George Schlossnagle</author> <publisher>Developer Library</publisher> <category>1</category> <category>3</category> </book> <book> <type>Fiction</type> <title>My Novel</title> <author>Same Nagle</author> <publisher>Developer Library</publisher> <category>1</category> <category>3</category> </book> I want to make the xml look like this: Code: [Select] <book> <type>nonFiction <title>Advanced PHP Programming</title> <author>George Schlossnagle</author> <publisher>Developer Library</publisher> <category>1</category> <category>3</category> </type> </book> <book> <type>Fiction <title>My Novel</title> <author>Same Nagle</author> <publisher>Developer Library</publisher> <category>1</category> <category>3</category> </type> </book> [attachment deleted by admin] |