how to load xml from this code please - php

I want to load the inside values from this xml code:
<?xml version="1.0" encoding="UTF-8"?>
<geoPlugin>
<geoplugin_city>Salt Lake City</geoplugin_city>
<geoplugin_region>UT</geoplugin_region>
<geoplugin_areaCode>801</geoplugin_areaCode>
<geoplugin_dmaCode>770</geoplugin_dmaCode>
<geoplugin_countryCode>US</geoplugin_countryCode>
<geoplugin_countryName>United States</geoplugin_countryName>
<geoplugin_continentCode>NA</geoplugin_continentCode>
<geoplugin_latitude>40.700199127197</geoplugin_latitude>
<geoplugin_longitude>-111.94339752197</geoplugin_longitude>
<geoplugin_regionCode>UT</geoplugin_regionCode>
<geoplugin_regionName>Utah</geoplugin_regionName>
<geoplugin_currencyCode>USD</geoplugin_currencyCode>
<geoplugin_currencySymbol>$</geoplugin_currencySymbol>
<geoplugin_currencyConverter>1</geoplugin_currencyConverter>
</geoPlugin>
If you can see the geoplugin_city, etc
I want to load these values to php
$location = 'http://www.geoplugin.net/xml.gp?ip='.$_SERVER['REMOTE_ADDR'];
$xml = simplexml_load_file($location);
that didn't work.
please help me out.
opps php i ment xml

It's not outputting XML, it's outputting serialized PHP data:
$location = 'http://www.geoplugin.net/php.gp?ip=192.168.1.1';
$file = unserialize(file_get_contents($location));
print_r($file);

Change your code to this first
$location = 'http://www.geoplugin.net/xml.gp?ip='.$_SERVER['REMOTE_ADDR'];
$xml = simplexml_load_file($location);
After that, make a Foreach loop to have all the data from that.
foreach ($xml as $keys => $values) {
$data[] = $values; // $data array have all your data independently.
}
Now, print the array and test the values.
echo "<pre>"; print_r($data); echo "</pre>";
However, try for dumping the variables so you will get the data types too..
var_dump($xml);

You will want to use the XML api instead of the PHP api.
$location = 'http://www.geoplugin.net/xml.gp?ip='.$_SERVER['REMOTE_ADDR'];
$xml = simplexml_load_file($location);

If you want the values in PHP, I would recommend not using the XML library at all.
$data = unserialize(file_get_contents('http://www.geoplugin.net/php.gpip='.$_SERVER['REMOTE_ADDR'])));
//Then access the data directly.
echo $data['geoplugin_city'];
echo $data['geoplugin_region'];

if you want to call the xml API the URL is
$location = 'http://www.geoplugin.net/xml.gp?ip='.$_SERVER['REMOTE_ADDR'];
$xml = simplexml_load_file($location);
Output Sample
<?xml version="1.0" encoding="UTF-8"?>
<geoPlugin>
<geoplugin_city>Lagos</geoplugin_city>
<geoplugin_region>Lagos</geoplugin_region>
<geoplugin_areaCode>0</geoplugin_areaCode>
<geoplugin_dmaCode>0</geoplugin_dmaCode>
<geoplugin_countryCode>NG</geoplugin_countryCode>
<geoplugin_countryName>Nigeria</geoplugin_countryName>
<geoplugin_continentCode>AF</geoplugin_continentCode>
<geoplugin_latitude>6.4531002044678</geoplugin_latitude>
<geoplugin_longitude>3.395800113678</geoplugin_longitude>
<geoplugin_regionCode>05</geoplugin_regionCode>
<geoplugin_regionName>Lagos</geoplugin_regionName>
<geoplugin_currencyCode>NGN</geoplugin_currencyCode>
<geoplugin_currencySymbol>₦</geoplugin_currencySymbol>
<geoplugin_currencyConverter>157.6899963379</geoplugin_currencyConverter>
</geoPlugin>
EDIT 1
echo "<pre>";
foreach($xml as $key => $value)
{
echo $key , " = " , $value , "\n" ;
}
Output
geoplugin_city = Lagos
geoplugin_region = Lagos
geoplugin_areaCode = 0
geoplugin_dmaCode = 0
geoplugin_countryCode = NG
geoplugin_countryName = Nigeria
geoplugin_continentCode = AF
geoplugin_latitude = 6.4531002044678
geoplugin_longitude = 3.395800113678
geoplugin_regionCode = 05
geoplugin_regionName = Lagos
geoplugin_currencyCode = NGN
geoplugin_currencySymbol = ₦
geoplugin_currencyConverter = 157.6899963379
Thanks
:)

Related

I am trying to scrap website but get only one array detail in xml file

I am trying to scrape this webpage. In this webpage I have to get the job title and its location. Which I am able to get from my code. But the problem is coming that when I am sending it in XML, then only one detail is going from the array list.
I am using goutte CSS selector library and also please tell me how to scrap pagination in goutte CSS selector library.
here is my code:
$httpClient = new \Goutte\Client();
$response = $httpClient->request('GET', 'https://www.simplyhired.com/search?q=pharmacy+technician&l=American+Canyon%2C+CA&job=X5clbvspTaqzIHlgOPNXJARu8o4ejpaOtgTprLm2CpPuoeOFjioGdQ');
$job_posting_location = [];
$response->filter('.LeftPane article .SerpJob-jobCard.card .jobposting-subtitle span.JobPosting-labelWithIcon.jobposting-location span.jobposting-location')
->each(function ($node) use (&$job_posting_location) {
$job_posting_location[] = $node->text() . PHP_EOL;
});
$joblocation = 0;
$response->filter('.LeftPane article .SerpJob-jobCard.card .jobposting-title-container h3 a')
->each( function ($node) use ($job_posting_location, &$joblocation, $httpClient) {
$job_title = $node->text() . PHP_EOL; //job title
$job_posting_location = $job_posting_location[$joblocation]; //job posting location
// display the result
$items = "{$job_title} # {$job_posting_location}\n\n";
global $results;
$result = explode('#', $items);
$results['job_title'] = $result[0];
$results['job_posting_location'] = $result[1];
$joblocation++;
});
function convertToXML($results, &$xml_user_info){
foreach($results as $key => $value){
if(is_array($value)){
$subnode = $xml_user_info->addChild($key);
foreach ($value as $k=>$v) {
$xml_user_info->addChild("$k",htmlspecialchars("$v"));
}
}else{
$xml_user_info->addChild("$key",htmlspecialchars("$value"));
}
}
return $xml_user_info->asXML();
}
$xml_user_info = new SimpleXMLElement('<root/>');
$xml_content = convertToXML($results,$xml_user_info);
$xmlFile = 'details.xml';
$handle = fopen($xmlFile, 'w') or die('Unable to open the file: '.$xmlFile);
if(fwrite($handle, $xml_content)) {
echo 'Successfully written to an XML file.';
}
else{
echo 'Error in file generating';
}
what i got in xml file --
<?xml version="1.0"?>
<root><job_title>Pharmacy Technician
</job_title><job_posting_location> Vallejo, CA
</job_posting_location></root>
what i want in xml file --
<?xml version="1.0"?>
<root>
<job_title>Pharmacy Technician</job_title>
<job_posting_location> Vallejo, CA</job_posting_location>
<job_title>Pharmacy Technician 1</job_title>
<job_posting_location> Vallejo, CA</job_posting_location>
<job_title>Pharmacy Technician New</job_title>
<job_posting_location> Vallejo, CA</job_posting_location>
and so on...
</root>
You overwrite the values in the $results variable. You're would need to do something like this to append:
$results[] = [
'job_title' => $result[0];
'job_posting_location' => $result[1]
];
However here is no need to put the data into an array at all, just create the
XML directly with DOM.
Both your selectors share the same start. Iterate the card and then fetch
related data.
$httpClient = new \Goutte\Client();
$response = $httpClient->request('GET', $url);
$document = new DOMDocument();
// append document element node
$postings = $document->appendChild($document->createElement('jobs'));
// iterate job posting cards
$response->filter('.LeftPane article .SerpJob-jobCard.card')->each(
function($jobCard) use ($document, $postings) {
// fetch data
$location = $jobCard
->filter(
'.jobposting-subtitle span.JobPosting-labelWithIcon.jobposting-location span.jobposting-location'
)
->text();
$title = $jobCard->filter('.jobposting-title-container h3 a')->text();
// append 'job' node to group data in result
$job = $postings->appendChild($document->createElement('job'));
// append data nodes
$job->appendChild($document->createElement('job_title'))->textContent = $title;
$job->appendChild($document->createElement('job_posting_location'))->textContent = $location;
}
);
echo $document->saveXML();

Parse XML to PHP using ID value

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"

XML parsing only some nodes - PHP

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;

inserting an object into an array of objects php

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!!

Extracting XML with PHP

I know how to use simplexml_load_file to get XML results if the XML format is
<bowlcontents>
<banana>yellow</banana>
<apple>red</apple>
</bowlcontents>
However, I have some code that is in the format
<bowlcontents>
<fruit type="banana" skin="yellow" />
<fruit type="apple" skin="red" />
</bowlcontents>
and I want to manipulate it in the same way as in the first example. How would I do this?
EDIT: This is precisely what I want to do, yet the code below doesn't work.
<?php
$url = "http://worldsfirstfruitAPI.com/fruit.xml";
$xml = (simplexml_load_file($url));
$results = array();
foreach ($xml->bowlcontents->fruit as $fruit) {
$results[] = array(
$fruit['type'] => $fruit['skin'],
);
}
return $results;
}
?>
So at the end of it I would like to have an array, key=value:
banana=yellow
apple=red
...
I hope this clarifies. Thanks!
As per PHP's manual, attributes are accessed using the array notation:
$bowlcontents->fruit['type'];
Come to think of it, you didn't say in your question what was your problem. If that's about iterating over nodes, you can do it using foreach.
/*
$bowlcontents = simplexml_load_string(
'<bowlcontents>
<fruit type="banana" skin="yellow" />
<fruit type="apple" skin="red" />
</bowlcontents>'
);
*/
$url = "http://worldsfirstfruitAPI.com/fruit.xml";
$bowlcontents = simplexml_load_file($url);
foreach ($bowlcontents->fruit as $fruit)
{
echo $fruit['type'], "'s skin is ", $fruit['skin'], "<br/>\n";
}

Categories