I am trying to get the car positions (if I can the cars state (gas, how clean, etc) from this site: https://carsharing.mvg-mobil.de/?ref=separate.
As far as I can tell they get their data from this URL:
https://carsharing.mvg-mobil.de/json/stations.php
Now I am having trouble converting that into usable XML format. I tried bringing it into String form by using
JSON.stringify()
and go from there but that didn't seem to work. What im having trouble with are the { and quotation marks
since your question is tagged as php, here is a simple code-snippet that will get you a xml-string:
<?php
//get json-string
$cars_json = file_get_contents("https://carsharing.mvg-mobil.de/json/stations.php");
//convert json to array
$cars_array = json_decode($cars_json,true);
//creat xml-object and fill recursive
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($cars_array, array ($xml, 'addChild'));
//create xml-string that can be saved
$cars_xmlstring = $xml->asXML();
echo $cars_xmlstring
?>
Related
Everything is about PHP.
I think example will do the best.
I want the node to be <shippingCost>23</shippingCost>. But instead, xml outputs me <shippingcost>23</shippingcost>. I want to connect to an private external API, which only accepts the first form.
I was trying to use DomDocument and SimpleXMLElement classes in PHP, no of them could output me xml code without case-folding to lowercase. I was searching for some options too in both, but no of them was about lowercasing.
$input_xml = new DOMDocument("1.0","utf-8");
$super_root = addChild($input_xml,$input_xml,'orderExport','');
// ^ this gives me <orderexport></orderexport>
...
function addChild($doc,$node,$marker,$value){
$temp = $doc->createElement($marker);
$temp->appendChild($doc->createTextNode($value));
$node->appendChild($temp);
return $temp;
}
...
addChild($input_xml,$shipping_info,'shippingEmail',$mail);
...
$output = $input_xml->saveXml()
I expect to get for example
<camelCase>123</camelCase>
tag, but i get
<camelcase>123</camelcase>
Im trying to load search result from an library api using Search and Retrieve via URL (SRU) at : https://data.norge.no/data/bibsys/bibsys-bibliotekbase-bibliografiske-data-sru
If you see the search result links there, its looks pretty much like XML but when i try like i have before with xml using the code below, it just returns a empty object,
SimpleXMLElement {#546}
whats going on here?
My php function in my laravel project:
public function bokId($bokid) {
$apiUrl = "http://sru.bibsys.no/search/biblio?version=1.2&operation=searchRetrieve&startRecord=1&maximumRecords=10&query=ibsen&recordSchema=marcxchange";
$filename = "bok.xml";
$xmlfile = file_get_contents($apiUrl);
file_put_contents($filename, $xmlfile); // xml file is saved.
$fileXml = simplexml_load_string($xmlfile);
dd($fileXml);
}
If i do:
dd($xmlfile);
instead, it echoes out like this:
Making me very confused that i cannot get an object to work with. Code i present have worked fine before.
It may be that the data your being provided ha changed format, but the data is still there and you can still use it. The main problem with using something like dd() is that it doesn't work well with SimpleXMLElements, it tends to have it's own idea of what you want to see of what data there is.
In this case the namespaces are the usual problem. But if you look at the following code you can see a quick way of getting the data from a specific namespace, which you can then easily access as normal. In this code I use ->children("srw", true) to say fetch all child elements that are in the namespace srw (the second argument indicates that this is the prefix and not the URL)...
$apiUrl = "http://sru.bibsys.no/search/biblio?version=1.2&operation=searchRetrieve&startRecord=1&maximumRecords=10&query=ibsen&recordSchema=marcxchange";
$filename = "bok.xml";
$xmlfile = file_get_contents($apiUrl);
file_put_contents($filename, $xmlfile); // xml file is saved.
$fileXml = simplexml_load_string($xmlfile);
foreach ( $fileXml->children("srw", true)->records->record as $record) {
echo "recordIdentifier=".$record->recordIdentifier.PHP_EOL;
}
This outputs...
recordIdentifier=792012771
recordIdentifier=941956423
recordIdentifier=941956466
recordIdentifier=950546232
recordIdentifier=802109055
recordIdentifier=910941041
recordIdentifier=940589451
recordIdentifier=951721941
recordIdentifier=080703852
recordIdentifier=011800283
As I'm not sure which data you want to retrieve as the title, I just wanted to show the idea of how to fetch data when you have a list of possibilities. In this example I'm using XPath to look in each <srw:record> element and find the <marc:datafield tag="100"...> element and in that the <marc:subfield code="a"> element. This is done using //marc:datafield[#tag='100']/marc:subfield[#code='a']. You may need to adjust the #tag= bit to the datafield your after and the #code= to point to the subfield your after.
$fileXml = simplexml_load_string($xmlfile);
$fileXml->registerXPathNamespace("marc","info:lc/xmlns/marcxchange-v1");
foreach ( $fileXml->children("srw", true)->records->record as $record) {
echo "recordIdentifier=".$record->recordIdentifier.PHP_EOL;
$data = $record->xpath("//marc:datafield[#tag='100']/marc:subfield[#code='a']");
$subData=$data[0]->children("marc", true);
echo "Data=".(string)$data[0].PHP_EOL;
}
$xml = simplexml_load_string($value);
$json = json_encode($xml); // convert the XML string to JSON
$array = json_decode($json,TRUE);
Attributes are missing after converting into array.
The <SampleData> value as you say is encoded, the simplest way to get this back to 'normal' is to use htmlspecialchars_decode() to convert all the symbols before loading the string into SimpleXML. The code below does this and then outputs various parts of the data as an example of how to display information...
$source = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=biosample&id=367368";
$value = file_get_contents($source);
$value = htmlspecialchars_decode($value);
$xml = simplexml_load_string($value);
// Access the DbBuild value
echo "DbBuild=".(string)$xml->DocumentSummarySet->DbBuild.PHP_EOL;
// The BioSample publication date attribute
echo "BioSample publication date=".(string)$xml->DocumentSummarySet->DocumentSummary->SampleData->BioSample['publication_date'].PHP_EOL;
// List the attributes name and value
foreach ( $xml->DocumentSummarySet->DocumentSummary->SampleData->BioSample->Attributes->Attribute as $attribute ) {
echo (string)$attribute['attribute_name']."=".(string)$attribute.PHP_EOL;
}
Some of the XML access looks long winded, but it's just a case of accessing the various levels of data in the document. $xml->DocumentSummarySet accesses the <DocumentSummarySet> element under the root elements. BioSample['publication_date'] is the publication_date attribute in the <BioSample> element and so on.
There is a really simple solution to this - delete these two lines of code:
$json = json_encode($xml); // convert the XML string to JSON
$array = json_decode($json,TRUE);
XML, JSON, and PHP arrays all have different rules about what kind of structures can be represented, so converting arbitrarily between them will always end up with edge cases where you're missing data. SimpleXML is, as the name says, designed to be simple to use, so you will be much better off actually using it:
$xml = simplexml_load_string($value);
// Now access your data from $xml; no further conversion is needed
Since you give no further information about what your XML looks like, I can't give any further information about how to process it, but there are extensive examples in the PHP manual, and refer here if there are namespaces (tags or attributes with : in their name).
Hi I have never used xml but need to now, so I am trying to quickly learn but struggling with the structure I think. This is just to display the weather at the top of someones website.
I want to display Melbourne weather using this xml link ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml
Basically I am trying get Melbourne forecast for 3 days (what ever just something that works) there is a forecast-period array [0] to [6]
I used this print_r to view the structure:
$url = "linkhere";
$xml = simplexml_load_file($url);
echo "<pre>";
print_r($xml);
and tried this just to get something:
$url = "linkhere";
$xml = simplexml_load_file($url);
$data = (string) $xml->forecast->area[52]->description;
echo $data;
Which gave me nothing (expected 'Melbourne'), obviously I need to learn and I am but if someone could help that would be great.
Because description is an attribute of <area>, you need to use
$data = (string) $xml->forecast->area[52]['description'];
I also wouldn't rely on Melbourne being the 52nd area node (though this is really up to the data maintainers). I'd go by its aac attribute as this appears to be unique, eg
$search = $xml->xpath('forecast/area[#aac="VIC_PT042"]');
if (count($search)) {
$melbourne = $search[0];
echo $melbourne['description'];
}
This is a working example for you:
<?php
$forecastdata = simplexml_load_file('ftp://ftp2.bom.gov.au/anon/gen/fwo/IDV10753.xml','SimpleXMLElement',LIBXML_NOCDATA);
foreach($forecastdata->forecast->area as $singleregion) {
$area = $singleregion['description'];
$weather = $singleregion->{'forecast-period'}->text;
echo $area.': '.$weather.'<hr />';
}
?>
You can edit the aforementioned example to extract the tags and attributes you want.
Always remember that a good practice to understand the structure of your XML object is printing out its content using, for instance, print_r
In the specific case of the XML you proposed, cities are specified through attributes (description). For this reason you have to read also those attributes using ['attribute name'] (see here for more information).
Notice also that the tag {'forecast-period'} is wrapped in curly brackets cause it contains a hyphen, and otherwise it wouldn generate an error.
I'm trying to access the individual member-fields of a JSON object in PHP from a JSON string but I can't to access the inner-json, all I get is Array.
This is the JSON string
data = (
{
"created_time" = "2018-10-07T04:42:39+0000";
id = 1069496473131329;
name = "NAME_0";
},
{
"created_time" = "2018-09-09T10:31:50+0000";
id = 955684974605664;
name = "NAME_1";
},
At the moment my code is:
$nameString = $_POST["nameData"];
$nameJsonString = json_encode($nameString, JSON_FORCE_OBJECT);
$jsonNameObj = json_decode($nameJsonString, true);
I've been trying to access the individual entry with:
$element = $jsonNameObj['data'][0];
But only receive Array.
Any help would be greatly appreciated,
Cheers :)
After checking the inputted JSON data, I've realised that it doesn't have a consistent form. As opposed to the overall structure being:
JSON -> List -> JSON
Instead, it's:
JSON -> List
The list contains individual elements that can be in a different order. Consequently, calling:
$element = $jsonNameObj['data'][0]['created_time'];
Works sometimes. As there are three-values/object, I can congregate these values into a trio.
I'm sure there's a way to condense this list into a fixed-JSON format but I'm not familiar with how I'd go about that.
At the moment, with a bit of logic on the back-end, I can retrieve the values.
Thanks for your help #Difster and #Osama!