Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active October 4, 2022 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/a10780065b925e520a54b0096a5d2b0e to your computer and use it in GitHub Desktop.
Save mtvbrianking/a10780065b925e520a54b0096a5d2b0e to your computer and use it in GitHub Desktop.
Get an item from xml by path.
<?php
// https://phpsandbox.io/n/steep-union-wnew-ndjxv
function xml_get(
SimpleXMLElement|string $xml,
string $path,
mixed $default = null
): mixed
{
if(! $xml instanceof SimpleXMLElement) {
$xml = simplexml_load_string($xml);
}
$value = $xml->xpath($path)[0] ?? null;
if(! $value) {
return $default;
}
$value = $value->count() > 1
? json_decode(json_encode($value), true)
: (string) $value;
return $value ?? $default;
}
$xml = <<<XML
<ns0:sptransferrequest xmlns:ns0="http://www.ericsson.com/em/emm/serviceprovider/v1_0/backend">
<sendingfri>FRI:test.sp/USER</sendingfri>
<receivingfri>FRI:256782123123/MSISDN</receivingfri>
<amount>
<amount>1000.00</amount>
<currency>UGX</currency>
</amount>
<providertransactionid>20221005_002</providertransactionid>
<sendernote>To 256782123123</sendernote>
<receivermessage>From Tester</receivermessage>
<referenceid>687e2e7e-f74a-44dd-b1ab-a516340f1565</referenceid>
</ns0:sptransferrequest>
XML;
// // $xml = new SimpleXMLElement($xml);
// $value = xml_get($xml, 'transactionid'); // null
// $value = xml_get($xml, 'transactionid', '10035424'); // 10035424
// $value = xml_get($xml, 'sendingfri'); // FRI:test.sp/USER
// $value = xml_get($xml, 'amount'); // ['amount' => '1000.00', 'currency' => 'UGX']
$value = xml_get($xml, 'amount/currency'); // EUR
print_r($value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment