Hi i have an xml data like this
<Product>
<ProductID>13078</ProductID>
<image1>
image_url
</image1>
<image2>
image_url
</image2>
<image3>
image_url
</image3>
</Product>
i want to access images
please help!!!
You can do it using SimpleXMLElement
$xml = simplexml_load_string($xmlString, "SimpleXMLElement");
$json = json_encode($xml);
$array = json_decode($json,TRUE);
unset($array['ProductID']); // You don't want 'ProductID' then You can remove it using unset().
$i=1;
foreach($array as $key=>$val){
echo $array['image'.$i]; // Here you can get all images in one echo
$i++;
}
if (file_exists('test.xml')) {
$xml = simplexml_load_file('test.xml');
print_r($xml);
}
you will get a result array
or else if you have XML string use this function
$xml = simplexml_load_string($string);
print_r($xml);
hope this will help you
Your Solution:
$string = '<Product>
<ProductID>13078</ProductID>
<image1>
image_url
</image1>
<image2>
image_url
</image2>
<image3>
image_url
</image3>
</Product>';
$xml = simplexml_load_string($string);
echo $xml->image1;
Related
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 can I echo xml values with php by calling their "columnId" and not the position in the array ? (The array is really long)
Here is a sample of the xml :
<Data>
<Value columnId="ITEMS_SOLD">68</Value>
<Value columnId="TOTAL_SALES">682</Value>
<Value columnId="SHIPPING_READY">29</Value>
...
</Data>
The following php gives me all of the values :
$url = 'XXX';
$xml = file_get_contents($url);
$feed = simplexml_load_string($xml) or die("Error: Cannot create object");
foreach($feed->Data->Value as $key => $value){
echo $value;
}
I would like to be able to use something like that in my document :
echo $feed->Data->Value['TOTAL_SALES'];
Thank you for your help.
echo $feed->Data->Value[1];
I have an another way for your solution. You can convert xml object into array and use this for further process. Try this code:
<?php
$url = 'XXX';
//Read xml data, If file exist...
if (file_exists($url)) {
//Load xml file...
$xml = simplexml_load_file($url);
$arrColumn = array();//Variable initialization...
$arrFromObj = (array) $xml;//Convert object to array...
$i = 0;//Variable initialization with value...
//Loop until data...
foreach($xml AS $arrKey => $arrData) {
$columnId = (string) $arrData['columnId'][0];//array object to string...
$arrColumn[$columnId] = $arrFromObj['Value'][$i];//assign data to array...
$i++;//Incremental variable...
}
} else {//Condition if file not exist and display message...
exit('Failed to open file');
}
?>
Above code will store result into array variable $arrColumn and result is:
Array
(
[ITEMS_SOLD] => 68
[TOTAL_SALES] => 682
[SHIPPING_READY] => 29
)
Hope this help you well!
Use XPath. SimpleXML and DOM support it, but SimpleXML has some limits (It can only fetch node lists).
SimpleXML
$feed = simplexml_load_string($xml);
var_dump(
(string)$feed->xpath('//Value[#columnId = "TOTAL_SALES"]')[0]
);
Output:
string(3) "682"
DOM
$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
var_dump(
$xpath->evaluate('string(//Value[#columnId = "TOTAL_SALES"])')
);
Output:
string(3) "682"
I have the following example XML:
<PRODUCTRATINGLIST>
<PRODUCT>
<VENDORREF>AC308A~</VENDORREF>
<RATING>100%</RATING>
<REVIEWCOUNT>7</REVIEWCOUNT>
</PRODUCT>
<PRODUCT>
<VENDORREF>AC308C~</VENDORREF>
<RATING>98%</RATING>
<REVIEWCOUNT>89</REVIEWCOUNT>
</PRODUCT>
</PRODUCTRATINGLIST>
I'm simply trying to extract each node under PRODUCT:
$ratings = simplexml_load_file("test.xml");
foreach ($ratings->PRODUCT as $rating){
$part = $rating->VENDORREF;
$rating = str_replace('%','',$rating->RATING);
$numReviews = $rating->REVIEWCOUNT;
}
If I then try to print each element e.g.
echo $part.' '.$rating.' '.$numReviews;
$numReviews is always blank and I have no idea why.
You are replacing the $rating array with a variable, fix it like this:
$part = $rating->VENDORREF;
$rating_string = str_replace('%','',$rating->RATING);
$numReviews = $rating->REVIEWCOUNT;
Check below code. You change the variable names.
$ratings = simplexml_load_file("test.xml");
foreach ($ratings->PRODUCT as $rating){
$part = $rating->VENDORREF;
$ratingVal = str_replace('%','',$rating->RATING);
$numReviews = $rating->REVIEWCOUNT;
}
echo $part.' '.$ratingVal.' '.$numReviews;
I have this XML:
<InternalData>
<DataSet>
<Table>
<Expire_x0>2050-12-12T00:00:00+02:00</Expire_x0>
</Table>
</DataSet>
</InternalData>
How do I get the value of the <Expire_x0> tag?
I tried this:
$result = $s->__call("XmlString",array($params));
$obj_pros = get_object_vars($result);
$xml = $obj_pros['XmlStringResult'];
$xml = simplexml_load_string($xml);
$x = $xml->getElementsByTagName("Expire_x0");
echo $x;
without success. What is wrong?
If I understand correctly, you're looking to get the value of the <Expire_x0> tag, for which you can use this code.
$xml = simple_xml_load_string($xml); //Load XML String
$xml = json_decode(json_encode($xml), true); //Convert to Standard PHP Array
$expire = $xml['InternalData']['DataSet']['Table']['Expire_x0']; //Find Tag Value
Either:
$dom = new DOMDocument;
$dom->loadXML($xml);
$expiresx0 = $dom->getElementsByTagName('Expire_x0');
foreach ($expiresx0 as $expirex0) {
echo $expirex0->nodeValue, PHP_EOL;
}
http://php.net/manual/de/domdocument.getelementsbytagname.php
Or:
$xml = simplexml_load_string(xml);
echo $xml->DataSet->Table->Expire_x0;
http://php.net/manual/de/function.simplexml-load-file.php
Looks like you mixed both.
try this
<?php
$k = '<InternalData>
<DataSet>
<Table>
<Expire_x0>2050-12-12T00:00:00+02:00</Expire_x0>
</Table>
</DataSet>
</InternalData>';
$xml = simplexml_load_string($k);
echo $xml->DataSet->Table->Expire_x0;
}
Output
2050-12-12T00:00:00+02:00
So many ways...
Which one is preferred?
is it better to use :
$dom = new DOMDocument;
$dom->loadXML($xml);
$expiresx0 = $dom->getElementsByTagName('Expire_x0');
or :
$xml2 = simplexml_load_string($xml);
$xml2 = json_decode(json_encode($xml2), true);
$expire = $xml2['DataSet']['Table']['Expire_x0'];
or maybe:
$xml1 = simplexml_load_string($xml);
$x = $xml1->DataSet[0]->Table[0]->Expire_x0;
echo $x;
?
You should use like:
$xml = simplexml_load_string($xml);
echo $xml->DataSet->Table->Expire_x0;
Do not use root tag InternalData
I am trying to write a php script which will insert an object into an array of objects which is originally in XML format. I need to insert the object at a specified index and then be able to re-write the xml file from which the data was pulled with the updated object. Here is the structure of my XML
<?xml version="1.0" encoding="UTF-8"?>
<Bars>
<Bar>
<BarName>Kam's</BarName>
<bar_id>0</bar_id>
<Bartenders>
<Bartender>
<fname>Max</fname>
<lname>Vest</lname>
<imageURL>http://uofi-bars.com/bartenderImages/maxvest.jpg</imageURL>
<shift>2</shift>
</Bartender>
</Bartenders>
<Events>
<Event>
<EventName>Kams event</EventName>
<date>08/10/1989</date>
</Event>
</Events>
<Specials>
<Special>Kam's Special 1</Special>
<Special>Kam's Special 2</Special>
</Specials>
</Bar>
So in other words, if I have a bartender who works at a bar with an id of bar_id = 0, I need to be able to insert that bartender into the array of bartenders for that particular bar.
I use the following php code to create the arrays from XML:
function objectsIntoArray($arrObjData, $arrSkipIndices = array())
{
$arrData = array();
// if input is object, convert into array
if (is_object($arrObjData)) {
$arrObjData = get_object_vars($arrObjData);
}
if (is_array($arrObjData)) {
foreach ($arrObjData as $index => $value) {
if (is_object($value) || is_array($value)) {
$value = objectsIntoArray($value, $arrSkipIndices); // recursive call
}
if (in_array($index, $arrSkipIndices)) {
continue;
}
$arrData[$index] = $value;
}
}
return $arrData;
}
$xmlUrl = "Bars.xml"; // XML
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
print_r($arrXml);
I guess I just don't know how to refer to this array of objects within an array of objects... Any help would be greatly appreciated!
Thanks!
if you just replace your code:
$xmlUrl = "Bars.xml"; // XML
$xmlStr = file_get_contents($xmlUrl);
$xmlObj = simplexml_load_string($xmlStr);
$arrXml = objectsIntoArray($xmlObj);
print_r($arrXml);
with this:
$xmlUrl = "Bars.xml"; // XML
$xmlStr = file_get_contents($xmlUrl);
$xml = new SimpleXMLElement($xmlStr);
$bartenders = $xml->xpath('//Bartenders');
$new_bartender = $bartenders[0]->addChild('Bartender');
$new_bartender->fname = 'test1';
$new_bartender->lname = 'test2';
$new_bartender->imgURL = 'http://test.com';
$new_bartender->shift = '0';
print_r($bartenders);
this should do the trick, just replace the values with appropriate values :) i hope this helps!!