get xml elemnts data with php - php

I get xml object using curl.
But I can not seem to enter xml elements data.
I tried using:
$sxe = new SimpleXMLElement($result);
$final_xml = $sxe->asXML();
echo $final_xml -> Answer -> Status;
With that example I got nothing.
OR
$xml = simplexml_load_string($sxe);
$json = json_encode($xml);
$array = json_decode($json);
With that example I got an array of the xml as a long string and each position in the array was different note in the xml string.
This is the xml output I get, that I want to retrieve data from:
how can I retrieve data from this xml or change it to JSON and then retrieve data?
Thanx
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<ns7:GetStopMonitoringServiceResponse xmlns:ns3="http://www.siri.org.uk/siri" xmlns:ns4="http://www.ifopt.org.uk/acsb" xmlns:ns5="http://www.ifopt.org.uk/ifopt" xmlns:ns6="http://datex2.eu/schema/1_0/1_0" xmlns:ns7="http://new.webservice.namespace">
<Answer>
<ns3:ResponseTimestamp>2014-12-04T11:11:55.585+02:00</ns3:ResponseTimestamp>
<ns3:ProducerRef>ISR Siri Server (141.10)</ns3:ProducerRef>
<ns3:ResponseMessageIdentifier>89061165</ns3:ResponseMessageIdentifier>
<ns3:RequestMessageRef>000234:1351677777:4684</ns3:RequestMessageRef>
<ns3:Status>true</ns3:Status>
<ns3:StopMonitoringDelivery version="IL2.7">
<ns3:ResponseTimestamp>2014-12-04T11:11:55.585+02:00</ns3:ResponseTimestamp>
<ns3:RequestMessageRef>0</ns3:RequestMessageRef>
<ns3:Status>true</ns3:Status>
<ns3:MonitoredStopVisit>
<ns3:RecordedAtTime>2014-12-04T11:11:00.000+02:00</ns3:RecordedAtTime>
<ns3:ItemIdentifier>1448001046</ns3:ItemIdentifier>
<ns3:MonitoringRef>40262</ns3:MonitoringRef>
<ns3:MonitoredVehicleJourney>
<ns3:LineRef>4687</ns3:LineRef>
<ns3:DirectionRef>3</ns3:DirectionRef>
<ns3:PublishedLineName>12</ns3:PublishedLineName>
<ns3:OperatorRef>3</ns3:OperatorRef>
<ns3:DestinationRef>40110</ns3:DestinationRef>
<ns3:OriginAimedDepartureTime>2014-12-04T10:45:00.000+02:00</ns3:OriginAimedDepartureTime>
<ns3:VehicleLocation>
<ns3:Longitude>34.94065475463867</ns3:Longitude>
<ns3:Latitude>32.428466796875</ns3:Latitude>
</ns3:VehicleLocation>
<ns3:MonitoredCall>
<ns3:StopPointRef>40262</ns3:StopPointRef>
<ns3:ExpectedArrivalTime>2014-12-04T11:12:00.000+02:00</ns3:ExpectedArrivalTime>
</ns3:MonitoredCall>
</ns3:MonitoredVehicleJourney>
</ns3:MonitoredStopVisit>
</ns3:StopMonitoringDelivery>
</Answer>
</ns7:GetStopMonitoringServiceResponse>
</S:Body>
</S:Envelope>

Try this test code:
<pre><?php
$entries = simplexml_load_file("test.xml");
$namespaces = $entries->getNamespaces(true);
var_dump($namespaces);
$ns3s = $entries->children($namespaces['S'])
->Body
->children($namespaces['ns7'])
->GetStopMonitoringServiceResponse
->children()
->Answer
->children($namespaces['ns3']);
var_dump($ns3s);

Related

PHP get specific data from xml file

This is XML file.
<?xml version="1.0" encoding="utf-8"?>
<UW xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/XMLSchema.xsd">
<UWdata>
<List>
<IdProduct>1</IdProduct>
<ProductName>product</ProductName>
<ProductNameDE>product</ProductNameDE>
<ProductNameEN>product</ProductNameEN>
<Uf>1</Uf>
<PSIg>1</PSIg>
<Ug>1</Ug>
</List>
</UWdata>
</UW>
$lines_array=file($url);
$lines_string=implode('',$lines_array);
$xml=simplexml_load_string($lines_string) or die("Error: Cannot create object");
I try with this
echo $xml->UWdata[1]->ProductName;
But it doesn't return anything.I want to return Product name.
Sample code, Use simplexml_load_string
<?php
$a = '<?xml version="1.0" encoding="utf-8"?>
<UW xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/XMLSchema.xsd">
<UWdata>
<List>
<IdProduct>1</IdProduct>
<ProductName>product</ProductName>
<ProductNameDE>product</ProductNameDE>
<ProductNameEN>product</ProductNameEN>
<Uf>1</Uf>
<PSIg>1</PSIg>
<Ug>1</Ug>
</List>
</UWdata>
</UW>';
$xml=simplexml_load_string($a) or die("Error: Cannot create object");
echo ($xml->UWdata->List->ProductName);
?>
When you load the xml file using the php simplexml_load_file function to a variable. The veritable becomes an object.
<?php
$xml=simplexml_load_file("/path/to/the/file.xml");
?>
So, in your case, the $xml variable becomes a multi-level object where every elements of xml file are key of the object. Like: UWdata.
So, as $xml is a multi-level object, to access the element under UWdata, under List under ProductName, you have to code like bellow.
echo $xml->UWdata->List->ProductName."<br>";
Here,
UWdata is the key of $xml object.
List is the key of UWdata.
ProductName is the key of List.
Finally, you will get the value of key element ProductName = product
I modified your script and put the xml in an external file called testxml.xml, as it should be. Always separate the function and the data it's supposed to handle. I used your xml like this:
<?xml version="1.0" encoding="utf-8"?>
<UW xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/XMLSchema.xsd">
<UWdata>
<List>
<IdProduct>1</IdProduct>
<ProductName>productTEST</ProductName>
<ProductNameDE>product</ProductNameDE>
<ProductNameEN>product</ProductNameEN>
<Uf>1</Uf>
<PSIg>1</PSIg>
<Ug>1</Ug>
</List>
</UWdata>
</UW>
And with the following script it returns productTEST only.
$xmlstr = file_get_contents('./testxml.xml');
$xml = simplexml_load_string($xmlstr);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
echo $array['UWdata']['List']['ProductName'];
Hope this helps.
//edit:
While I do not know your project, you might want to take a foreach-approach if it is possible for your xml to contain more than one List element

How to move XML file data to PHP array?

This is my xml data
<?xml version="1.0" encoding="iso-8859-1"?>
<smslist>
<sms>
<cid>FIRSTCID</cid>
<mid>FIRSTMID</mid>
<mb>98389923</mb>
</sms>
<sms>
<cid>SECONDCID</cid>
<mid>SECONDMID</mid>
<mb>76445645</mb>
</sms>
...
</smslist>
How to push cid and mid data to php array like $array = array(("FIRSTCID","FIRSTMID"),("SECONDCID","SECONDMID")...)
Excuse if this is some duplicate question. :)
you can try this:
$xml = new SimpleXMLElement($your_xml_string);
$xml_array=[];
foreach ($xml->smslist->sms as $sms) {
$xml_array[]=array($sms->cid,$sms->mid);
}
By using xml_parse_into_struct() you can convert XML to array, for detailed document check below link.
http://php.net/manual/en/function.xml-parse-into-struct.php

Get value from a CDATA in xml

I dont know how get a lat, lon in php values from this xml code:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>OpenCellID Cells</name>
<description>List of available cells</description>
<Placemark><name></name><description><![CDATA[lat: <b>3.378199</b><br/>lon: <b>-76.523528</b><br/>mcc: <b>732</b><br/>mnc: <b>123</b><br/>lac: <b>4003</b><br/>cellid: <b>26249364</b><br/>averageSignalStrength: <b>0</b><br/>samples: <b>10</b><br/>changeable: <b>1</b>]]></description><Point><coordinates>-76.523528,3.378199,0</coordinates></Point></Placemark>
</Document>
</kml>
I hope you can help me with this. Thanks
The trick is to read out the cdata as a string first, let libxml wrap it into welformatted html and then parse out the values from the nodes containing your data.
Note that this works but assumes that lon and lat are always in the first nodes in the cdata
// the xml as a variable
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>OpenCellID Cells</name>
<description>List of available cells</description>
<Placemark><name></name><description><![CDATA[lat: <b>3.378199</b><br/>lon: <b>-76.523528</b><br/>mcc: <b>732</b><br/>mnc: <b>123</b><br/>lac: <b>4003</b><br/>cellid: <b>26249364</b><br/>averageSignalStrength: <b>0</b><br/>samples: <b>10</b><br/>changeable: <b>1</b>]]></description><Point><coordinates>-76.523528,3.378199,0</coordinates></Point></Placemark>
</Document>
</kml>';
// read into dom
$domdoc = new DOMDocument();
$domdoc->loadXML($xml);
// the cdata as a string
$cdata = $docdom->getElementsByTagName('Placemark')->item(0)->getElementsByTagName('description')->item(0)->nodeValue;
// a dom object for the cdata
$htmldom = new DOMDocument();
// wrap in html and parse
$htmldom->loadHTML($cdata);
// get the <b> nodes
$bnodes = $htmldom->getElementsByTagName('b');
// your data :)
$lon = $bnodes->item(0)->nodeValue;
$lat = $bnodes->item(1)->nodeValue;
Last not least, this is to illustrate how loadXML and loadHTML differ and how to use that. As for googleeart kml, I am sure that is a more standard way to parse ...

XML file creation using PHP [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
XML formatting is not working well
I am trying to create an XML file from the database. Database contains name, phone no and sex. I would like to get all the users' details in a well-formatted XML file. But I am getting now:
<CUSTOMERS>
<name>AAA</name>
<name>BBB</name>
</CUSTOMERS>
This is my code:
$xmlstr = "<?xml version='1.0' ?>\n"."<CUSTOMERS></CUSTOMERS>";
$xml = new SimpleXMLElement($xmlstr);
while($b=$result->fetch_assoc()){
$xml->addChild("name", $b['name']);
}
return $xml->asXML();
I would like to get the out put as shows below
<CUSTOMERS>
<AAAA>
<name>AAA</name>
<phone>111</phone>
<sex>male</sex>
</AAA>
<BBBB>
<name>BBB</name>
<phone>222</phone>
<sex>female</sex>
</AAA>
</CUSTOMERS>
Latest Code
$xmlstr = "<?xml version='1.0' ?>\n"."<CUSTOMERS></CUSTOMERS>";
$xml = new SimpleXMLElement($xmlstr);
while($b=$result->fetch_assoc()){
$customer = $xml->addChild("customer");
$customer->addChild("name", $b['name']);
$customer->addChild("phone", $b['phone']);
$customer->addChild("sex", $b['sex']);
//$xml->addChild("place", $b['place']);
}
return $xml->asXML();
Each customer should be in its own tag:
$d = simplexml_load_string('<?xml version="1.0" encoding="utf-8" ?><customers />');
$customer = $d->addChild('customer');
$customer->addChild('name', 'Jack');
// $customer->addChild('phone', '911');
// etc.
$customer = $d->addChild('customer');
$customer->addChild('name', 'John');
echo $d->asXML();
<?xml version="1.0" encoding="utf-8"?>
<customers>
<customer><name>Jack</name></customer>
<customer><name>John</name></customer>
</customers>
Note that the tag name should not be the name of your customer, it should rather be a description of what information is inside; hence my use of the customer tag.
You should be able to do it like this:
$xml = new SimpleXMLElement("<customers></customers>");
while($b=$result->fetch_assoc()){
$customer = $xml->addChild("customer");
$customer->addChild("name", $b['name']);
$customer->addChild("phone", $b['phone']);
$customer->addChild("sex", $b['sex']);
}
Output:
<customers>
<customer>
<name>AAA</name>
<phone>1234567</phone>
<sex>f</sex>
</customer>
</customers>
You are telling PHP to add the <name> child but nothing else.
$xml->addChild("name", $b['name']);
In that while loop, you need to add the <AAA> element, then the child <name>, <phone>, and <sex> (and etc) elements.
The question is to change this
$xmlstr = "<?xml version='1.0' ?>\n"."<CUSTOMERS></CUSTOMERS>";
to this
$xmlstr = = '<' . '?xml version='1.0' ?>\n"."<CUSTOMERS></CUSTOMERS>';
As the <? messes up the parser.
Also XML does not like capitals and needs a root - i.e. something between your customers.

How do I parse an individual entry from XML using PHP?

I am trying to parse an individual element from an XML string using PHP. The issue is that this individual element occurs before the entries start. The XML is below:
<?xml version="1.0" encoding="UTF-8"?>
<feed gd:kind="shopping#products" gd:etag=""lm_25heFT8yiumci9EH1kItJBpg/Sj5O9aXZ82PKpx3N2C3uQYMhNYE"" xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:s="http://www.google.com/shopping/api/schemas/2010">
<openSearch:totalResults>64</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>25</openSearch:itemsPerPage>
<entry >...</entry>
<entry >...</entry>
</feed>
I am trying to parse out the "64" in the opensearch:totalResults tag. How do I this and assign it to a variable in php? I tried:
$url = 'url of xml feed';
$xml = simplexml_load_file($url);
$entries =$xml->entry[0]->openSearch:totalResults;
// also tried $entries =$xml->openSearch:totalResults;
echo $entries;
but it's not working. Any advice?
You need to register namespace in order to access these nodes:
$xml = simplexml_load_file('file.xml');
$xml->registerXPathNamespace('os', 'http://a9.com/-/spec/opensearchrss/1.0/');
$nodes = $xml->xpath('os:totalResults');
$totalResults = (string)$nodes[0];
You can also use http://it1.php.net/manual/en/simplexmlelement.children.php (using the $ns parameter)
that is less resource intensive.

Categories