How parsing xml from url and get attribute php - php

I need parsing xml from file to parsing, but i can parsing only local file, how i can parsing file from url?
I use this php code
<?php
include '/example1.php';
$string = $xmlstr;
$xml = simplexml_load_string($string);
foreach($xml->row->exchangerate[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>
example1.php code
<?php
$xmlstr = <<<XML
<exchangerates>
<row>
<exchangerate ccy="RUR" base_ccy="UAH" buy="0.33291" sale="0.33291"/>
</row>
<row>
<exchangerate ccy="EUR" base_ccy="UAH" buy="18.60253" sale="18.60253"/>
</row>
<row>
<exchangerate ccy="USD" base_ccy="UAH" buy="14.97306" sale="14.97306"/>
</row>
</exchangerates>
XML;
?>

Just feed the necessary url and use simplexml_load_file() of you want to use the url:
$url = 'https://api.privatbank.ua/p24api/pubinfo?exchange&coursid=3';
$xml = simplexml_load_file($url);
foreach($xml->row[0]->exchangerate->attributes() as $key => $exchangerate) {
if($key == 'buy' || $key == 'sale') {
$exchangerate = 10 * (float) $exchangerate;
}
echo '<div id="attribute_'.$key.'"></div>','<div id="valuta">'.$exchangerate.'</div><br/>';
}

what about download the xml before loading
<?php
$string = file_get_contents("https://www.unicreditbank.cz/web/exchange_rates_xml.php");
?>
like this
<?php
$string = file_get_contents("https://www.unicreditbank.cz/web/exchange_rates_xml.php");
$xml = simplexml_load_string($string);
foreach($xml->row->exchangerate[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>

Related

How to get 2 child ID value from XML?

I wanted to try to pick up Volume value from the Level1Data node.
Here is the xml:
<Response>
<Content>
<Level1Data Tick="U" Currency="USD" TickSize="0.0001000000" TickValue="0" AssetClass="Equity" InstrumentState="Open" LastPrice="24.1550" LotSize="10"
MinPermittedPrice="0" MaxPermittedPrice="0" ClosePrice="24.0300" OpenPrice="24.1500" FirstPrice="24.1500"
HighPrice="24.7800" LowPrice="24.0000" MaxPrice="24.7800" MinPrice="24.0000" Volume="16238302"
AskSize="105597" BidSize="97618" AskPrice="24.1600" BidPrice="24.1500" Symbol="BAC.NY"
MarketTime="12:08:41.356" Message="L1DB"/>
</Content>
</Response>
And then my main script:
<?php
$result = file_get_contents("lvl1.xml");
// echo $result;
$xml = new SimpleXMLElement($result);
// $dom = new DOMDocument();
// $dom->loadXML("lvl1.xml");
// $vol = dom->getElementsByTagName('Level1Data');
$vol=$xml->children->children('Level1Data');
$id = $xml["Volume"];
echo $id;
?>
Nothing gets returned and I am having a hard time reading the php documentation and their examples.
Thank you.
You can try to find the XML node using attributes() and foreach what attribute you want as per your requirements. If you need only single attribute then discard foreach looping.
<?php
$result =<<<EOT
<Response>
<Content>
<Level1Data Tick="U" Currency="USD" TickSize="0.0001000000" TickValue="0" AssetClass="Equity" InstrumentState="Open" LastPrice="24.1550" LotSize="10"
MinPermittedPrice="0" MaxPermittedPrice="0" ClosePrice="24.0300" OpenPrice="24.1500" FirstPrice="24.1500"
HighPrice="24.7800" LowPrice="24.0000" MaxPrice="24.7800" MinPrice="24.0000" Volume="16238302"
AskSize="105597" BidSize="97618" AskPrice="24.1600" BidPrice="24.1500" Symbol="BAC.NY"
MarketTime="12:08:41.356" Message="L1DB"/>
</Content>
</Response>
EOT;
$volume = '';
$xml = new SimpleXMLElement($result);
foreach($xml->Content->Level1Data[0]->attributes() as $a => $b) {
if($a=='Volume'){
$volume = $b;
}
}
echo $volume;
?>
Demo https://eval.in/839942
OR for single attribute e.g Volume
echo $xml->Content->Level1Data[0]->attributes()->Volume;
If you want to pickup Volume only, it can also be done as follows.
<?php
$result = <<<EOM
<Response>
<Content>
<Level1Data Tick="U" Currency="USD" TickSize="0.0001000000" TickValue="0" AssetClass="Equity" InstrumentState="Open" LastPrice="24.1550" LotSize="10"
MinPermittedPrice="0" MaxPermittedPrice="0" ClosePrice="24.0300" OpenPrice="24.1500" FirstPrice="24.1500"
HighPrice="24.7800" LowPrice="24.0000" MaxPrice="24.7800" MinPrice="24.0000" Volume="16238302"
AskSize="105597" BidSize="97618" AskPrice="24.1600" BidPrice="24.1500" Symbol="BAC.NY"
MarketTime="12:08:41.356" Message="L1DB"/>
</Content>
</Response>
EOM;
$xml = new SimpleXMLElement($result);
echo $xml->Content->Level1Data[0]->attributes()->Volume;
EDIT
<?php
$result = <<<EOM
<Response>
<Content>
<Level1Data Tick="U" Currency="USD" TickSize="0.0001000000" TickValue="0" AssetClass="Equity" InstrumentState="Open" LastPrice="24.1550" LotSize="10"
MinPermittedPrice="0" MaxPermittedPrice="0" ClosePrice="24.0300" OpenPrice="24.1500" FirstPrice="24.1500"
HighPrice="24.7800" LowPrice="24.0000" MaxPrice="24.7800" MinPrice="24.0000" Volume="16238302"
AskSize="105597" BidSize="97618" AskPrice="24.1600" BidPrice="24.1500" Symbol="BAC.NY"
MarketTime="12:08:41.356" Message="L1DB"/>
</Content>
</Response>
EOM;
$xml = new SimpleXMLElement($result);
function recur($obj){
if ( in_array('Level1Data', array_keys( (array) $obj->children()) ) === false){
recur($obj->children());
}else{
var_dump($obj->children()->Level1Data);
exit;
}
}
recur($xml);

how to dynamically change the value of an xml node with php

<?xml version="1.0" encoding="UTF-8" ?>
<SMS>
<authentification>
<username>xxxx</username>
<password>xxxx</password>
</authentification>
<recipients>
<number>8309042932</number>
</recipients>
</SMS>
my number node has a dynamically generated numbers for different people, i want to load all the numbers, but am getting only the last number.
Code used to create the xml string:
<?xml version="1.0" encoding="UTF-8" ?>
$xmlstring =
"<SMS>
<authentification>
<username>xxxx</username>
<password>xxxx</password>
</authentification>
<recipients>";
foreach($gsmnumbers as $number) {
$number = explode(",", $number);
foreach($number as $num) {
$count = count($num);
for($i = 0; $i < $count; $i++) {
$xmlHalf = "<gsm>$num</gsm>";
}
}
}
$xmlSecondHalf = "</recipients> </SMS>";
Try this, all sorts of mistakes in your code.
Basically if you use the .= syntax, you can concatenate to the end of an existing string where just using = will replace the string with the new value.
Also the <?xml version="1.0" encoding="UTF-8" ?> need to be in the string to identify it as a valid XML string.
$xmlstring = '
<?xml version="1.0" encoding="UTF-8" ?>
<SMS>
<authentification>
<username>xxxx</username>
<password>xxxx</password>
</authentification>
<recipients>';
foreach($gsmnumbers as $number) {
$nums = explode(",", $number);
foreach($nums as $num) {
$xmlstring .= "<gsm>$num</gsm>";
}
}
$xmlstring .= "</recipients></SMS>";
Don't write XML as string, use a XML library for that. A library normally prevents you from shooting into your own foot when it comes to creating XML. It also makes your code more readable. Example:
// process and transform input data
$gsmnumbers = ['1234,5678,9012'];
$gsms = [];
foreach ($gsmnumbers as $number) {
$nums = explode(",", $number);
foreach ($nums as $num) {
$gsms[] = $num;
}
}
// create XML
$request = new SimpleXMLElement('<SMS/>');
$authentication = $request->addChild('authentification');
$authentication->username = 'XXXX';
$authentication->password = 'XXXX';
$recipients = $request->addChild('recipients');
foreach ($gsms as $gsm) {
$recipients->addChild('gsm', $gsm);
}
echo $request->asXML();
Example output:
<?xml version="1.0"?>
<SMS><authentification><username>XXXX</username><password>XXXX</password></authentification><recipients><gsm>1234</gsm><gsm>5678</gsm><gsm>9012</gsm></recipients></SMS>

Get data from an xml file

In a php script how to read and convert a XML document to an object and access the obtained object in order to get his data?
<?php
$xml ='<?xml version="1.0" encoding="UTF-8" ?>
<data request-id="ID">
<data name="Name1"
d1="0"
d2="0231234"
d3="32584">
<data name="Name2"
d4="231234"
d5="2012-06-06 18:18:10.000607"
d6="3b048653-aaa9-485b-b0dd-d16e068230e9" />
</data>
</data>';
$xml = simplexml_load_string($xml);
//how to get the data d1? or d4? from the obtained object
?>
You can use this snippet:
<?php
$xmlstring = file_get_contents($filename);
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$object = json_decode($json);
Try using this function -
$xml ='<?xml version="1.0" encoding="UTF-8" ?>
<data request-id="ID">
<data name="Name1"
d1="0"
d2="0231234"
d3="32584">
<data name="Name2"
d4="231234"
d5="2012-06-06 18:18:10.000607"
d6="3b048653-aaa9-485b-b0dd-d16e068230e9" />
</data>
</data>';
function xmlToArray($input, $callback = null, $recurse = false) {
$data = ((!$recurse) && is_string($input))? simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA): $input;
if ($data instanceof SimpleXMLElement) $data = (array) $data;
if (is_array($data)) foreach ($data as &$item) $item = xmlToArray($item, $callback, true);
return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
$xml = xmlToArray($xml);
echo $xml['data']['#attributes']['d1'];
echo '<br/>';
echo $xml['data']['data']['#attributes']['d4'];
Use
$myxml = simplexml_load_string($xml);
echo $myxml->data[1]['d1'];
echo $myxml->data[1]['d2'];
echo $myxml->data[1]['d3'];
echo $myxml->data[2]['d4'];
Reference : How to parse XML with PHP5
try :-
echo $xml['data']['#attributes']['d1'];
echo '<br/>';
echo $xml['data']['data']['#attributes']['d4'];

Can I use SQL syntax on SimpleXML?

Can I use a WHERE selector (like SQL syntax) on SimpleXML?
Example XML
<?xml version="1.0" encoding="utf-8" ?>
<documentElement>
<row>
<id>1</id>
<name>David</name>
<surname>Johnson</surname>
</row>
<row>
<id>2</id>
<name>Jack</name>
<surname>Nixon</surname>
</row>
</documentElement>
My Example Where Selector
$where = "Jack";
$xml = "example.xml";
$sxml = simplexml_load_string($xml);
foreach ($sxml->row as $data=>$row)
{
if ($where == $data->name) // some code here
else // other some code here
}
Please let me know.
Thank you.
Yes, there is a way: XPath
$where = "Jack";
$xml = "example.xml";
$sxml = simplexml_load_string($xml);
var_dump($sxml->xpath('/documentElement/row/name[.="'.$where.'"]/..'));
No, but you can do this:
$where = "Jack";
$xml = "example.xml";
$sxml = simplexml_load_string($xml);
foreach ($sxml->row as $row)
{
if ($row->name == $where) {
// ...
} else {
// other some code here
}
}

Import XML with attributes into mysql

I have a large (~30Mb) XML file like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<LIC Version="2.0" Title="Products">
<Item>
<Field Name="Filename">/root/_DOWNLOAD/Bird.txt</Field>
<Field Name="Read_By">Lisa Hannigan</Field>
<Field Name="Posit">Passenger</Field>
</Item>
<Item>
<Field Name="Filename">D:\03\Strypers.pdf</Field>
<Field Name="Read_By">Stryper</Field>
<Field Name="Intensity">2</Field>
<Field Name="IMG">78</Field>
<Field Name="Rotate">0</Field>
</Item>
<Item>
<Field Name="Filename">D:\Afriu.txt</Field>
<Field Name="Read_By">Africano</Field>
<Field Name="Posit">Canto Africano vol.1</Field>
<Field Name="File_Resource">mp3</Field>
</Item>
<Item>
<Field Name="Filename">D:\_VARIOUS\Knots.pdf</Field>
<Field Name="Date">40624</Field>
</Item>
...
</LIC>
I want to import this xml into mysql database, with a php script. I've used SIMPLEXML and xpath:
$url = 'FILE.xml';
$xml = simplexml_load_file($url);
$result = $xml->xpath("//Field[#Name]");
foreach { ... }
What do i need? What is the correct "foreach" to create an array to use for mysql sql?
Notes that every row (identify by "Item") is not same (not have the same "Field Name").
Is it correct to use simplexml for larger file?
Thank you for help!
update
This is an example to use "foreach", i tried:
$result = $xml->xpath("//Field[#Name]");
foreach($result as $key => $value) {
echo $value['Name']."=".$value.",";
}
Now I want to find out how to create the string to insert in mysql
First create a table that matches all possible fields as columns. Then you can load it by a LOAD XML LOCAL INFILE query.
LOAD XML LOCAL INFILE 'file.xml'
INTO TABLE person
ROWS IDENTIFIED BY '<Item>';
I try to answer my question.
<?php
$url = 'FILEXML';
$xml = simplexml_load_file($url);
$i = 1;
foreach($xml->xpath("/LIC/Item") as $docs)
{
foreach($docs->Field as $field)
{
$resultstr[] = $field["Name"];
}
$sql_head = headquote($resultstr);
$sql_ins = "INSERT INTO table_name (";
$sql_dec = ") VALUE (";
unset($resultstr);
$fresult = (array)$docs;
$fvalue = array_pop($fresult);
$sql_val = numking($fvalue);
$sql_end = ");";
$query_to_use_for_mysql = ($sql_ins.$sql_head.$sql_dec.$sql_val.$sql_end);
unset($fresult);
unset($fvalue);
}
?>
And add this two functions:
<?php
function headquote($hdarray) {
$hdata = array();
foreach ( $hdarray as $hdval ) {
# Use backticks instead quotes!
$hdata[] = "`$hdval`";
}
$hdarray = implode($hdata, ',');
return $hdarray;
}
function numking($input) {
$data = array();
foreach ( $input as $value ) {
$data[] = is_numeric($value) ? $value : "'".mysql_escape_string($value)."'";
}
$input = implode($data, ',');
return $input;
}
?>
Thanks to all for help!
$url = 'FILE.xml';
$xml = simplexml_load_file($url);
for($i=0;$i<count($xml->Item);$i++)
{
print_r($xml->Item[$i]);
}

Categories