Load and parse XML file with PHP [duplicate] - php

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 9 years ago.
I have to create a webservice which goes to a specific URL that returns a XML-file as response and interprets/parses this file in order to save its contents to a MySQL database.
I've heard about the SimpleXML but I'm not sure how to get the websites response into a file whose path is needed in order to parse the document.
Can somebody at least explain me how to reach the goal of downloading the XML and saving it to a file? (best with some PHP code)
I will then (hopefully) find out by myself how to parse it and store its contents.
Here's an example of what my XML will look like (for privacy reasons I can't publish the real URL I'm using...)

Here's a couple of pointers..
To download a file and save it, the easiest way I have found is this:
<?php
file_put_contents('saved.xml', file_get_contents('http://www.xmlfiles.com/examples/simple.xml'));
You can then open the file with the simpleXML library like so:
$xml = simplexml_load_file('saved.xml');
var_dump($xml);
Hope that gives you enough info to get started.
See simpleXML for info on the simpleXML library.

You can download and save the xml to a local file by doing this:
$xmlstring = file_get_contents("http://domain.com/webservice/xmlfile.xml");
file_put_contents("path/localxmlfile.xml", $xmlstring);
To parse the xml file I suggest you to use DOMDocument class in combination with the DOMXPath class to query/search for specific elements.
DOMDocument: http://php.net/manual/de/class.domdocument.php
DOMXPath: http://php.net/manual/de/class.domxpath.php

Hopefully you can find your answer on below link. Seems related topic.
How do you parse and process HTML/XML in PHP?

Related

Remove XML Node from a file loaded using PHP filesystem [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 4 years ago.
I have an XML file that's read using PHP's file_get_contents so other changes can be done to it.
I need to find and remove the nodes <BATCHALLOCATIONS.LIST>...<BATCHALLOCATIONS.LIST> (not just those two lines, but what's between the entire node) in the entire file.
Since the file is already loaded using file_get_contents I'd like to do this without having to load the file again using simpleXML, or an XML parser or any other method (like DOM).
The node does not have a specific parent and appears randomly.
The XML file is exported from a Business Accounting Software.
Any idea on how to achieve this? Maybe using a Regular Expression to do a search and replace or something like that?
I've been trying to do this using a regular expression and preg_replace, but just can't get things to work.
Here's just a portion of the file. The original runs to 10K+ lines.
This should have worked but doesn't
preg_replace('/^\<BATCHALLOCATIONS.LIST\>(.*?)\<\BATCHALLOCATIONS.LIST\>$/ism','', $newXML);
I'm trying to do this without using any HTML/XML parser.
There's probably a better way to do it, but this will work
// get your file as a string
$yourXML = file_get_contents($file) ;
$posStart = stripos($yourXML,'<BATCHALLOCATIONS.LIST>') ;
$posEnd = stripos($yourXML,'</BATCHALLOCATIONS.LIST>') + strlen('</BATCHALLOCATIONS.LIST>') ;
$newXML = substr($yourXML,0,$posStart) . substr($yourXML,$posEnd) ;

Read only Title from a page? [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 7 years ago.
I have a page called index.php which has some content on it, but the title is set from another server that generates a text file called cache_currentsongcallapi.txt
Contents of 'cache_currentsongapi.txt':
<tracks>
<radioname>Mick&apos;s Music Station</radioname>
<rank>0</rank>
<isradionomy>1</isradionomy>
<radurl>http://www.radionomy.com/mick-smusicstation</radurl>
<track>
<uniqueid>2722440231</uniqueid>
<title>Hello</title>
<artists>Adele</artists>
<starttime>2015-11-23 21:05:02.35</starttime>
<playduration>293023</playduration>
<current>1</current>
<callmeback>217256</callmeback>
</track>
</tracks>
Is there any way that I can take ONLY the title from the text file and display it in the index page?
NOTE:
This method cannot include editing the text file as it is overwritten by the server.
The website that this code will go on: http://mickyd.net/radio
This appears like valid XML. Never, never read XML using regular expressions. You'll hear this a lot, and for good reasons.
I'd start by reading the string as XML:
$xml = new SimpleXMLElement($string);
$result = $xml->xpath('/tracks/track/title');
Your mileage may vary, but basically you can do a lot starting from here. I'd suggest reading a bit more on DOMXPath and SimpleXMLElement.
Here's a full version including the reading of the actual file since you seem to need help there too, but please mark Victor's as the answer.
$filePath = "file.txt";
$handle = fopen($filePath, "r");
$fileContents = fread($handle, filesize($filePath));
$xml = new SimpleXMLElement($fileContents);
$title = $xml->xpath("/tracks/track/title");
echo($title[0]);
Where "file.txt" is the path to the file.

PHP. XML parsing from variable [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 9 years ago.
I've such piece of code:
$xml=”<response>
<version>1.2</version>
<merchant_id></merchant_id>
<order_id> ORDER_123456</order_id>
<amount>1.01</amount>
<currency>UAH</currency>
<description>Comment</description>
<status>success</status>
<code></code>
<transaction_id>31</transaction_id>
<pay_way>card</pay_way>
<sender_phone>+3801234567890</sender_phone>
<goods_id>1234</goods_id>
<pays_count>5</pays_count>
</response>";
Could I parse it? How to do it? I had never work with XML.
E.g how to take ?
You should use simplexml_load_string function.
Parse as follow:
echo simplexml_load_string($xml)->version;
There is plenty functions you could use have a look at the link above.
Try saving your XML to a file and use simplexml to parse it in php.
See tutorial here: http://blog.teamtreehouse.com/how-to-parse-xml-with-php5
You should use DomDocument. It is much more flexible and useful than SimpleXML.
Parse as follows:
$doc = new DOMDocument();
$doc->loadXML($xml);
$price = $doc->getElementsByTagName('amount');
$currency = $doc->getElementsByTagName('currency');

Extracting XML data to php [duplicate]

This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 9 years ago.
I'm trying to extract data from XML file (http://freegeoip.net/xml/google.com). You can see the content of the file looks something like:
<Response>
<Ip>74.125.235.3</Ip>
<CountryCode>US</CountryCode>
<CountryName>United States</CountryName>
<RegionCode>CA</RegionCode>
<RegionName>California</RegionName>
<City>Mountain View</City>
<ZipCode>94043</ZipCode>
<Latitude>37.4192</Latitude>
<Longitude>-122.0574</Longitude>
<MetroCode>807</MetroCode>
<AreaCode>650</AreaCode>
</Response>
I want to take the information stored in the <latitude> and <longitude> tags, and store them in separate variables. The problem is, I've little idea how to do this, and was wondering if anyone could show me how to parse XML files with php?
$string_data = "<your xml response>";
$xml = simplexml_load_string($string_data);
$latitude = (string) $xml->Latitude;
$longitude = (string) $xml->Longitude;
echo $latitude.' '.$longitude;
It's easy, use PHP's SimpleXML Library:
$xml = simplexml_load_file("http://freegeoip.net/xml/google.com");
echo $xml->Ip; // 173.194.38.174
echo $xml->CountryCode; // US
echo $xml->ZipCode; // 94043
// etc...
The PHP manual has a whole section on PHP parsing:
http://php.net/manual/en/book.simplexml.php
http://php.net/manual/en/book.xml.php
For simplicity, you could also use xml_parse_into_struct()
Here's a pretty good example, using SimpleXML:
http://blog.teamtreehouse.com/how-to-parse-xml-with-php5

Use SimpleXML to grab nested code [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
php simplexml issue in reading an attribute that has a ‘column - : ’ in its name
I'm in the process of learning PHP, so I'm making a weather app to display an image based on the weather. I'm using the Yahoo Weather API.
My problem is that I'm looking for a way to grab the code of the weather, located next to yweather:condition . I found simpleXML but can't figure out how to grab something that's located in something like the way Yahoo does its xml in the form of
<yweather:condition text="Fair" code="34" temp="37"
So my question is how can I grab the code="34" portion of the Yahoo weather and display it as a variable like $weathercode = 34;?
Thanks for any and all help, and I'm here to give more details if you need them!
Also, I'm not sure if the title of this post is correct, so sorry if it's not!
You can use the SimpleXMLElement::attributes call in a similar way to below.
$string = {Yahoo Weather Feed}
$xml = simplexml_load_string($string);
$weathercode = $xml->channel->item->children('yweather', true)->condition[0]->attributes()->code;
You may need to tinker to get it right, but this is just a guide.
Reference: http://php.net/manual/en/simplexmlelement.attributes.php
You could try the following:
$xml = simplexml_load_file('http://weather.yahooapis.com/forecastrss?w=12793465&u=f');
var_dump($xml);
This will load the URL and dump the SimpleXML object.
More on simplexml_load_file here

Categories