Read XML data from string [duplicate] - php

This question already has answers here:
Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?
(2 answers)
Closed 2 years ago.
now i need to ask this, have this XML:
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.telemetry.udo.fors.ru/" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<soapenv:Header>
<wsse:Security soapenv:mustUnderstand="1">
<wsse:UsernameToken>
<wsse:Username/>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"/>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<web:storeTelemetryList xmlns="http://webservice.telemetry.udo.fors.ru/">
<telemetryWithDetails xmlns="">
<telemetry>
<coordX>-108.345268</coordX>
<coordY>25.511797</coordY>
<date>2020-04-16T16:48:07Z</date><glonass>0</glonass>
<gpsCode>459971</gpsCode>
<speed>0</speed>
</telemetry>
</telemetryWithDetails>
</web:storeTelemetryList>
</soapenv:Body>
</soapenv:Envelope>
and im using simplexml on PHP to read it but i get the error "Trying to get property 'telemetryWithDetails' of non-object" when i try to get the data in coordx, coordy,date, gpscode and speed node but i cant get there here is my code:
$string = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope...(same from above)
XML;
$xml = new SimpleXMLElement($string);
echo $xml->Body->storeTelemetryList->telemetryWithDetails;
if i put "->telemetryWithDetails->telemetry->coordX" i get "Trying to get property 'telemetry' of non-object, Trying to get property 'coordX' of non-object" and the same if use "simplexml_load_string" Hope you can help me thanks

A simple solution is to use XPath and describe the "path" to the values you want :
$xml = simplexml_load_string($xmlstring);
$telemetries = $xml->xpath('/soapenv:Envelope/soapenv:Body/web:storeTelemetryList/telemetryWithDetails/telemetry');
$telemetry = $telemetries[0] ;
$coordX = (string) $telemetry->xpath('./coordX')[0] ;
$coordY = (string) $telemetry->xpath('./coordY')[0] ;
echo $coordX ; //-108.345268
echo $coordY ; // 25.511797
XPath returns always a collection, so select the first node with [0]. The (string) conversion is used to extract the text value inside the node.

Related

simplexml_load_string asXML not empty, but children() function returns empty? [duplicate]

This question already has answers here:
SimpleXMLElement Access elements with namespace?
(4 answers)
Closed 1 year ago.
echo $xml->asXML();
Prints the following, and I am tring to access to elements here like: InvoiceStateResult
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<soap:Header>
<wsa:Action>http://tempuri.org/SendEArchiveDataResponse</wsa:Action>
<wsa:MessageID>urn:uuid:72e8aaf0-b36d-422f-ab0b-486c17c50c83</wsa:MessageID>
<wsa:RelatesTo>urn:uuid:fc0a3e9d-40c1-4f3b-9517-8002825b7217</wsa:RelatesTo>
<wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
<wsse:Security>
<wsu:Timestamp wsu:Id="Timestamp-3a82271a-a910-4062-81aa-984468387047">
<wsu:Created>2021-05-28T12:12:23Z</wsu:Created>
<wsu:Expires>2021-05-28T12:27:23Z</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</soap:Header>
<soap:Body>
<SendEArchiveDataResponse
xmlns="http://tempuri.org/">
<SendEArchiveDataResult>
<Invoices>
<InvoiceStateResult>
<ServiceResult>Error</ServiceResult>
<UUID>11111111-2222-3333-4444-555555555555</UUID>
<InvoiceId>T612014000000053</InvoiceId>
<StatusDescription>INVOICE EXISTS</StatusDescription>
<StatusCode>29</StatusCode>
<ErrorCode>0</ErrorCode>
<ReferenceNo>T612014000000053</ReferenceNo>
</InvoiceStateResult>
</Invoices>
<ServiceResult>Error</ServiceResult>
<ServiceResultDescription>This invoice processed before InvoiceId : TRL2021000000019 , UUID : DB3642EB-7A5F-40FD-8DF8-A922CA113837 SenderTaxID : 3324502175 . </ServiceResultDescription>
<Source>IntegrationWebService</Source>
<ErrorCode>30</ErrorCode>
<invoiceCount>1</invoiceCount>
</SendEArchiveDataResult>
</SendEArchiveDataResponse>
</soap:Body>
</soap:Envelope>
However I couldn't reach any of the nodes. I tried this:
foreach($xml->children() as $child) {
echo "Child node: " . $child . "</br>";
}
and it returns empty.
How will I access the nodes ?
Thanks
Simple XML, is - as the name suggests, a very simple implementation and it looks for standard namespaces. You can use registerXPathNamespace to look for non custom ones. See example below that works for your code.
$xml = simplexml_load_string($string);
$xml->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
print_r($xml->xpath('//soap:Body')[0]->SendEArchiveDataResponse->SendEArchiveDataResult->Invoices->InvoiceStateResult);

PHP XML not parsing with SimpleXml [duplicate]

This question already has answers here:
Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?
(2 answers)
Closed 2 years ago.
my xml not parsing, i have no idea why
First line of xml not parsing, but second line parsing good
I know about im missings whatever in code, but searched in google and not find correct answer for it
// this xml not work, with <soap:Envelope> tags
$string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetBrandsListResponse xmlns="http://tempuri.org/">
<GetBrandsListResult>
<DocumentElement>
<BrandLst>
<ID>1</ID>
<Name>Audi</Name>
</BrandLst>
<BrandLst>
<ID>350</ID>
<Name>BMW</Name>
</BrandLst>
</DocumentElement>
</GetBrandsListResult>
</GetBrandsListResponse>
</soap:Body>
</soap:Envelope>';
// but this xml works, without soap envelope tags
$string = '
<BrandLst>
<ID>1</ID>
<Name>Audi</Name>
</BrandLst>
';
$xml = simplexml_load_string($string);
var_dump($xml);
Fixed with adding xpath and registerXPathNamespace
$xml = simplexml_load_string($string);
$xml->registerXPathNamespace('default', 'http://tempuri.org/');
$auto = $xml->xpath("//default:BrandLst");

How i can get sessionid from this SOAPXML

I want to get sessionid from this XML piece of code:
<soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:header>
<soapenv:body>
<p725:loginresponse xmlns:p725="http://www.fleetboard.com/data">
<p725:loginresponse sessionid="0001nABbah-I8f75oDrVbHrBgOv:s96fb0a4m3"></p725:loginresponse>
</p725:loginresponse>
</soapenv:body>
</soapenv:header>
</soapenv:envelope>
I have tried this but this doesn't work:
$soap=simplexml_load_string($result);
$xml_response = $soap->children('http://schemas.xmlsoap.org/soap/envelope/')->Body()->children()->p725;
echo $session_id = (int) $xml_response->session_id;
There are two ways to do this. The first is as you are currently doing it, but this involves various changes of namespace and means you need to keep on getting the right child elements and the attribute itself...
$soap=simplexml_load_string($result);
$xml_response = $soap->children("http://schemas.xmlsoap.org/soap/envelope/")->header->body;
$session_id = $xml_response->children("http://www.fleetboard.com/data")->loginresponse->loginresponse;
echo $session_id->attributes()->sessionid.PHP_EOL;
Or you can use XPath, where you will need to register the namespace with the document first and then select the loginresponse element with a sessionid element. This will return a list of matches, so you have to take the first one using [0]...
$soap=simplexml_load_string($result);
$soap->registerXPathNamespace("p725", "http://www.fleetboard.com/data");
$session_id = $soap->xpath("//p725:loginresponse/#sessionid");
echo $session_id[0];

SOAP XML inside XML - How to parse with PHP

I've searched in the SO, but nothing what i've found could help me.
I'm doing system integration with JadLog, a freight service.
When I pass the query with the product and delivery variables, an XML is returned.
Return example:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<valorarResponse xmlns="">
<ns1:valorarReturn xmlns:ns1="http://jadlogEdiws">
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://www.jadlog.com.br/JadlogEdiWs/services">
<Jadlog_Valor_Frete>
<versao>1.0</versao>
<Retorno>1458,62</Retorno>
<Mensagem>Valor do Frete</Mensagem>
</Jadlog_Valor_Frete>
</string>
</ns1:valorarReturn>
</valorarResponse>
</soapenv:Body>
</soapenv:Envelope>
So, there is more than one XML declaration, right?
The only value that I need is the value of the freight, wich is in the tag Retorno. I this case, 1458,62.
What am I trying to do:
$your_xml_response = file_get_contents($url_project);
$clean_xml = str_replace('soapenv:', '', $your_xml_response);
$xml = simplexml_load_string($clean_xml);
var_dump($xml);
What its returns:
object(SimpleXMLElement)[1]
public 'Body' =>
object(SimpleXMLElement)[2]
public 'valorarResponse' =>
object(SimpleXMLElement)[3]
If I try to echo $xml->Retorno, it Returns empty.
How can I get the value of tag Retorno?
When I tried to load your XML string with simplexml_load_string it causes me
There is more than one XML declaration which is not allowed in xml . That's why I used regular express to get Retorno value. May be its not the best approach to use regex on XML but you can make a try.
<?php
$re = '/<Retorno>(.*?)<\/Retorno>/m';
$str = '<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<valorarResponse xmlns="">
<ns1:valorarReturn xmlns:ns1="http://jadlogEdiws">
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://www.jadlog.com.br/JadlogEdiWs/services">
<Jadlog_Valor_Frete>
<versao>1.0</versao>
<Retorno>1458,62</Retorno>
<Mensagem>Valor do Frete</Mensagem>
</Jadlog_Valor_Frete>
</string>
</ns1:valorarReturn>
</valorarResponse>
</soapenv:Body>
</soapenv:Envelope>
';
preg_match_all($re, $str, $matches);
//debugging
print '<pre>';
print_r($matches);
print '<pre>';
//result
echo $matches[0][0];

how to add prefix and URI on xml objects (PHP)

in this sample found here:
<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>
We create an xml object from scratch. all righ.
my question is, how to embed a prefix in a tag during the construction of the object?
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header />
<soapenv:Body>
<EnviarLoteRpsEnvio xmlns="http://www.betha.com.br/e-nota-contribuinte-ws">
...some important xml...
</EnviarLoteRpsEnvio>
</soapenv:Body>
</soapenv:Envelope>
in this code above, show a final xml, how, during the create of xml object, i embed the prefixes in the tags? sorry for my bugged english..
thanks for all help.

Categories