I am building an iphone app which allows people to update an xml file by sending a POST to a php script. After they send the post to the php script and the xml is updated, I would like the user to be able to cancel the update to the XML. How can I delete just one element from the XML and rewrite the XML file to the same location on the server (in other words, just the one element is now gone, everything else is the same)? To add an element I used code that looks like the following:
$xmlUrl = "Bars.xml"; // XML
$xmlStr = file_get_contents($xmlUrl);
$xml = new SimpleXMLElement($xmlStr);
$bartenders = $xml->xpath('//Bartenders');
$new_bartender = $bartenders[$newBar_ID]->addChild('Bartender');
$new_bartender->fname = $newfname;
$new_bartender->lname = $newlname;
$new_bartender->imageURL = $newimageURL;
$new_bartender->shift = $newShift;
print_r($bartenders);
$xml->asXML('Bars.xml');
When I send the POST method to the php script, I have the element's attribute to identify which is to be deleted.
Thanks for your help.
Possible duplicate of THIS.
From your code snippet I don't really know what data is given. You could try to do either
unset($bartenders[$newBar_ID]);
or
$bartenders->removeChild($bartenders[$newBar_ID]);
I guess... I wrote these based on code snippets google turned up, never tested them. Feel free to give me feedback if it works or not.
Related
I have a response that I got from a server using PHP, it is returned in XML format. Unfortunately I cannot disclose the code that is in question since it is for a client, but here is a shortened version of it:
// server request code here…
$result = $soap>__doRequest($xmltosend,URL,$action,1); //the final part of the request process…
// $result is the returned xml that is to be converted into a separate file
Is there any way that I could take the returned XML and make a new file? If you have any questions I will be more than happy to answer them!
Thanks in advance!
Try it with DOMDocument:
$doc = new DOMDocument();
$doc->loadXML($result);
$doc->save("/tmp/your-document.xml");
You can find more on this in the php documentation
I'm attempting to use the Zoopla API (http://developer.zoopla.com/docs/read/Property_listings) to output specific data.
I have tested the API using a simple echo after the "file_get_contents() method, which shows the data. Example code shown below (API Key Removed)
$url = "http://api.zoopla.co.uk/api/v1/property_listings.xml?postcode=CF11&api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$zoopla = file_get_contents($url);
echo $zoopla;
What Im trying to code is a loop that will allow me to add html tags so that I can style them. I've done similar for a RSS feed but can't figure out a way for this XML.
I have also tried an alternative approach using simplexml_load_file()
$xml = simplexml_load_file($url);
$agent_address = $xml->agent_address->agent_address[1]->agent_address;
echo $agent_address;
Any help would be greatly appreciated!
I found the answer to my own question!
Basically the $URL is a string and not a file "simplexml_load_file()"
So first, we need to get the xml file as a string and then parse the file. Code as followed! Works like a treat!
$zoopla = file_get_contents('http://api.zoopla.co.uk/api/v1/property_listings.xml?postcode=CF64&api_key=xxxxxxxxxxxxxxxxx');
$properties = simplexml_load_string($zoopla);
echo $properties->listing[2]->agent_phone;
I am trying to change a value in an xml file using php. I am loading the xml file using php into an object like this..
if(file_exists('../XML/example.xml')) {
$example = simplexml_load_file('../XML/example.xml');
}
else {
exit ("can't load the file");
}
Then once it is loaded I am changing values within tags, by assigning them the contents of another variable, like this...
$example->first_section->second_section->third_section->title = $var['data'];
Then once I've made the necessary changes the file is saved. So far this process is working well, but have now hit a stumbling block.
I want to change a value within a particular tag in my xml file, which has an id. In the XML file it looks like this.
<first_section>
<second_section>
<third_section id="2">
<title>Mrs</title>
</third_section>
</second_section>
</first_section>
How can I change this value using similar syntax to what I've been using?
doing..
$example->first_section->second_section->third_section id="2" ->title = $var['data']
doesn't work as the syntax is wrong.
I've been scanning through stack overflow, and all over the net for an example of doing it this way but come up empty.
Is it possible to target and change a value in an xml like this, or do I need to change the way I am amending this file?
Thanks.
Some dummy code as your provided XML is surely not the original one.
$xml = simplexml_load_file('../XML/example.xml');
$section = $xml->xpath("//third_section[#id='2']")[0];
// runs a query on the xml tree
// gives always back an array, so pick the first one directly
$section["id"] = "3";
// check if it has indeed changed
echo $xml->asXML();
As #Muhammed M. already said, check the SimpleXML documentation for more information. Check the corresponding demo on ideone.com.
Figured it our after much messing around. Thanks to your contributions I indeed needed to use Xpath. However the reason it wasn't working for me was because I wasn't specifying the entire path for the node I wanted to edit.
For example, after loading the xml file into an object ($xml):
foreach($xml->xpath("/first_section/second_section/third_section[#id='2']") as $entry ) {
$entry->title = "mr";
}
This will work, because the whole path to the node is included in the parenthesis.
But in our above examples eg:
foreach($xml->xpath("//third_section[#id='2']" as $entry ) {
$entry->title = "mr";
}
This wouldn't work, even though it was my understanding that the double // will make it drill down, and I assumed that xpath will search the whole xml structure and return where id=2. It appears after spending hours testing this isn't the case. You must include the entire path to the node. As soon as I did that it worked.
Also on a side note. $section = $xml->xpath("//third_section[#id='2']")[0];
IS incorrect syntax. You don't need to specify the index "[0]" at the end. Including it flags up Dreamweavers syntax checker. And ignoring Dreamweaver and uploading anyway breaks the code. All you need is..
$section = $xml->xpath(" entire path to node in here [#id='2']");
Thanks for helping and suggesting xpath. It works very well... once you know how to use it.
UPDATE: The source code is very much different from what Developer Tools shows.
Check out the source: view-source:http://www.machinerytrader.com/list/list.aspx?ETID=1&catid=1002
Is that javascript that needs to be rendered by a browser into html? If so, how can I have php do that process so that I have Html to parse? It's weird that you can use Xpath Checker to return the items I'm looking for (see below), but you cannot access the full html!
(Xpath: //table[contains(#id, 'ctl00_ContentPlaceHolder1') and (contains(#id,"tblContent") or contains(#id,"tblListingHeader"))])
END UPDATE
I need to scrape some information off of this site for work on a regular basis. I am attempting to write some PHP code to scrape this data. I think I have some namespace issues here, having read a number of other posts on SO. I have never encountered namespace problems before and used the approach shown on another SO post (to no avail :().
It appears the xpath query is just not happening for whatever reason. If you have any guesses or solutions as to how to handle this issue, I am open for suggestions.
Also here is the output from my code:
object(DOMXPath)#2 (0) {
}
Debug 1
array(0) {
}
array(0) {
}
I left out the bottom of the code where I var_dump testarray and create and var_dump otherarray. Their output is included above. Obviously the two arrays will be empty if the DOMXPath element has length 0 as well.
$string = 'http://www.machinerytrader.com/list/list.aspx?ETID=1&catid=1002';
$machine_trader = file_get_contents($string);
$xml = new DOMDocument();
$xml->loadHTML($machine_trader);
$xpath = new DOMXPath($xml);
$rootNamespace = $xml->lookupNamespaceUri($xml->namespaceURI);
$xpath->registerNamespace('x', $rootNamespace);
$tableRows = $xpath->query("//x:table[contains(#id, 'ctl00_ContentPlaceHolder1') and (contains(#id,'tblContent') or contains(#id,'tblListingHeader'))]");
var_dump($xpath);
$testarray = array();
$otherarray = array();
foreach ( $tableRows as $row )
{
echo "Debug 1"."\n";
$testarray[] = $row->nodeValue;
}
This is not an XPath issue insofar that the actual content is found from a form post, which you didn't reach yet. JS Source code here does nothing more than authenticate a proper 'user' for the information request, and then send the request via form submission.
At each request, the salt / encryption 'key' is randomized and changes, preventing simple scrapes.
You could rewrite that JavaScript to PHP and then issue two requests, battling the authentication process along the way.
Or, rather than diddle with reverse-engineering this, you could switch your scraping to NodeJS and use something like PhantomJS since it can evaluate javascript but give you programmatic access. Given the complexity of this task, it'd be much simpler to use the right tool.
I need to store the XML that i get it from Google Analytics. Its format is XML file. I need to create the script ( PHP ) that will read XML file from Google Analytics and store in my server with user defined name. I tried like that
<?php
$dom = new DOMDocument();
$dom->load('https://www.google.com/analytics/reporting/export?fmt=1&id=346044461&pdr=20100611-20100711&cmp=average&rpt=DashboardReport');
$dom->save('books3.xml');
?>
Can you help me
you're not assigning the result of load to anything you can save afterwards. and that is assuming you created a function load.
you'd need something more along the lines of
<?php
$remoteUri = 'https://www.google.com/analytics/reporting/export?...';
$doc = new DOMDocument();
$doc->loadXML(file_get_contents($remoteUri));
$xml = $doc->saveXML($doc->documentElement);
file_put_contents($yourLocalFilePath, $xml);
or if you just want a completely verbatim copy locally:
<?php
$remoteUri = ...
file_put_contents($yourLocalFilePath, file_get_contents($remoteUri));
the second, simpler version doesn't attempt to parse any xml and will therefore not have any clue if something is wrong with the recieved document.
depending on your server, you might have to resort to more complex methods of getting the file if url wrappers for fopen aren't enabled, or if your google endpoint wants to use cookies etc. for example.