2

Necesito crear una rutina con php donde extraiga uel valor de una etiqueta por medio del atributo id de un archivo xml.

Hay dos formas de hacerlo:

1.tener en una variable en php que contenga ese valor del atriubot id y cada que lea el archivo xml lo compara y lo extraiga.

  1. Usando una clase de php donde extraiga colocandole el codigo del atributo id.

Ejemplo del archivo xml es este:

    <AttachedDocument xmlns="urn:oasis:names:specification:ubl:schema:xsd:AttachedDocument-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ccts="urn:un:unece:uncefact:data:specification:CoreComponentTypeSchemaModule:2" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:xades141="http://uri.etsi.org/01903/v1.4.1#"><cbc:UBLVersionID>UBL 2.1</cbc:UBLVersionID><cbc:CustomizationID>Documentos adjuntos</cbc:CustomizationID><cbc:ProfileID>DIAN 2.1</cbc:ProfileID><cbc:ProfileExecutionID>1</cbc:ProfileExecutionID><cbc:ID>TD263479</cbc:ID><cbc:IssueDate>2021-05-31</cbc:IssueDate><cbc:IssueTime>21:47:50-05:00</cbc:IssueTime><cbc:DocumentType>Contenedor de Factura Electrónica</cbc:DocumentType><cbc:ParentDocumentID>TD263479</cbc:ParentDocumentID><cac:SenderParty><cac:PartyTaxScheme><cbc:RegistrationName>TODOMED LTDA</cbc:RegistrationName><cbc:CompanyID schemeAgencyID="195" schemeAgencyName="CO, DIAN (direccion)" schemeID="4" schemeName="31">815005074</cbc:CompanyID><cbc:TaxLevelCode listName="48">R-99-PN</cbc:TaxLevelCode><cac:TaxScheme><cbc:ID>01</cbc:ID><cbc:Name>IVA</cbc:Name></cac:TaxScheme></cac:PartyTaxScheme></cac:SenderParty><cac:ReceiverParty><cac:PartyTaxScheme><cbc:RegistrationName>CAJA DE COMPENSACION FAMILIAR DE NARIÑO</cbc:RegistrationName><cbc:CompanyID schemeAgencyID="195" schemeAgencyName="CO, DIAN (direccion)" schemeID="1" schemeName="31">891280008</cbc:CompanyID><cbc:TaxLevelCode listName="48">R-99-PN</cbc:TaxLevelCode><cac:TaxScheme><cbc:ID>01</cbc:ID><cbc:Name>IVA</cbc:Name></cac:TaxScheme></cac:PartyTaxScheme></cac:ReceiverParty><cac:Attachment><cac:ExternalReference><cbc:MimeCode>text/xml</cbc:MimeCode><cbc:EncodingCode>UTF-8</cbc:EncodingCode><cbc:Description><![CDATA[<?xml version="1.0" encoding="utf-8" standalone="no"?><Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:sts="dian:gov:co:facturaelectronica:Structures-2-1" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:xades141="http://uri.etsi.org/01903/v1.4.1#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd"><ext:UBLExtensions><ext:UBLExtension><ext:ExtensionContent><sts:DianExtensions><sts:InvoiceControl><sts:InvoiceAuthorization>18764001534394</sts:InvoiceAuthorization><sts:AuthorizationPeriod><cbc:StartDate>2020-08-01</cbc:StartDate><cbc:EndDate>2021-08-01</cbc:EndDate></sts:AuthorizationPeriod><sts:AuthorizedInvoices><sts:Prefix>TD</sts:Prefix><sts:From>215000</sts:From><sts:To>275000</sts:To></sts:AuthorizedInvoices></sts:InvoiceControl><sts:InvoiceSource>
                       <cbc:IdentificationCode listAgencyID="6" listAgencyName="United Nations Economic Commission for Europe" listSchemeURI="urn:oasis:names:specification:ubl:codelist:gc:CountryIdentificationCode-2.1">CO</cbc:IdentificationCode>
                   </sts:InvoiceSource>
                   <sts:SoftwareProvider>
                        <sts:ProviderID schemeAgencyID="195" schemeAgencyName="CO, prueba (direccion)" schemeID="0" schemeName="31">890930534</sts:ProviderID>
                        <sts:SoftwareID schemeAgencyID="195" schemeAgencyName="CO, prueba (direccion)">49fab599-4556-4828-a30b-852a910c5bb1</sts:SoftwareID>
                   </sts:SoftwareProvider>
                    <sts:SoftwareSecurityCode schemeAgencyID="195" schemeAgencyName="CO, prueba (direccion)">596c04d8a5205efcc3b91ddb7d3d94d126c4c8e46188bb708438469eb8635b6c852c25cac5b9bd5b893d5c1419f5590f</sts:SoftwareSecurityCode>
                   <sts:AuthorizationProvider>
                       <sts:AuthorizationProviderID schemeAgencyID="195" schemeAgencyName="CO, prueba (direccion)" schemeID="4" schemeName="31">800197268</sts:AuthorizationProviderID>
                    </sts:AuthorizationProvider>
                   <sts:QRCode>NroFactura=EF7894
                    NitFacturador=815605074
                    NitAdquiriente=855995060
                    FechaFactura=2020-08-31
                    HoraFactura=15:57:06-05:00
                    ValorFactura=1000000.00
                    ValorIVA=0.00
                    ValorOtrosImpuestos=0.00
                    ValorTotalFactura=1000000.00
                    </sts:QRCode>
              </sts:PruebaExtensions></ext:ExtensionContent></ext:UBLExtension><ext:UBLExtension><ext:ExtensionContent><ds:Signature Id="xmldsig-e038b630-632e-47e7-be42-6ca07c7b9e5b"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/><ds:Reference Id="xmldsig-e038b630-632e-47e7-be42-6ca07c7b9e5b-ref0" URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><ds:DigestValue>JJ97shgQUkoeAyw+N2/eLvXUf06WyAeFlRNOHxQOTZY=</ds:DigestValue></ds:Reference><ds:Reference URI="#xmldsig-e038b630-632e-47e7-be42-6ca07c7b9e5b-keyinfo"><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><ds:DigestValue>YU8ZKJQu2zrU3wI9u3jcCYv3rTB0rqGLy89oeJc0EHo=</ds:DigestValue></ds:Reference><ds:Reference Type="http://uri.etsi.org/01903#SignedProperties" URI="#xmldsig-e038b630-632e-47e7-be42-6ca07c7b9e5b-signedprops"><ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/><ds:DigestValue>dBCWb9NlJ7jJxXm8C7io1cbS042dRoYCO1oi0bKPCWU=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue Id="xmldsig-e038b730-632e-47e7-be42-6ca07c7b9e5b-sigvalue">Dljl5RIE3XgLsI8jIKZzBBxDpLSAZ1wk3aoEiyGZrej0ZhLOZKfzhH5r5mx5pgdFwtznFca8iFW3/aGXqfHLUugvq8q7l6i0AnCYQHQBRIFzhPZpCws08v6A2eUjYI4h/g3DvAxjCYrEUtC8R6d32GKQt3SzCeYPf4+KQGRZL73xhce1wAzBiHp9GGX7OZEQfw4szeNLcvI1PQizXxe9SM/vUmWe+sgwPgAlaLNaeX4PQ3kmo6GDtxz1FoGi4Pccr3m8D3LuJq2hl2BgezV3uN8NJ38VhbEzjCGpoVG3sXuIDbXty10cv0Z0gjF7eTDyrwO3x1M24bz5S93fx+uQsg==</ds:SignatureValue></xades:SigPolicyHash></xades:SignaturePolicyId></xades:SignaturePolicyIdentifier><xades:SignerRole><xades:ClaimedRoles><xades:ClaimedRole>third party</xades:ClaimedRole></xades:ClaimedRoles></xades:SignerRole></xades:SignedSignatureProperties></xades:SignedProperties></xades:QualifyingProperties></ds:Object></ds:Signature></ext:ExtensionContent></ext:UBLExtension></ext:UBLExtensions><cbc:UBLVersionID>UBL 2.1</cbc:UBLVersionID>
    <
    </cac:LineResponse>
    <cac:LineResponse>
      <cac:LineReference>
        <cbc:LineID>2</cbc:LineID>
      </cac:LineReference>
      <cac:Response>
        <cbc:ResponseCode>0</cbc:ResponseCode>
        <cbc:Description>La Factura electrónica BC-458566 ha sido autorizada.</cbc:Description>
      </cac:Response>
    </cac:LineResponse>
  </cac:DocumentResponse>
</ApplicationResponse>]]></cbc:Description></cac:ExternalReference></cac:Attachment><cac:ResultOfVerification><cbc:ValidatorID>Unidad Especial direccion</cbc:ValidatorID><cbc:ValidationResultCode>02</cbc:ValidationResultCode><cbc:ValidationDate>2021-05-31</cbc:ValidationDate><cbc:ValidationTime>16:47:50-05:00</cbc:ValidationTime></cac:ResultOfVerification></cac:DocumentReference></cac:ParentDocumentLineReference></AttachedDocument>

este es la parte que del id que deseo comparar para extraerlo:

<ds:SignatureValue Id="xmldsig-e038b730-632e-47e7-be42-6ca07c7b9e5b-sigvalue">Dljl5RIE3XgLsI8jIKZzBBxDpLSAZ1wk3aoEiyGZrej0ZhLOZKfzhH5r5mx5pgdFwtznFca8iFW3/aGXqfHLUugvq8q7l6i0AnCYQHQBRIFzhPZpCws08v6A2eUjYI4h/g3DvAxjCYrEUtC8R6d32GKQt3SzCeYPf4+KQGRZL73xhce1wAzBiHp9GGX7OZEQfw4szeNLcvI1PQizXxe9SM/vUmWe+sgwPgAlaLNaeX4PQ3kmo7GDtxz1FoGi4Pccr3m8D3LuJq2hl2BgezV3uN8NJ38VhbEzjCGpoVG3sXuIDbXty10cv0Z0gjF7eTDyrwO3x1M24bz5S93fx+uQsg==</ds:SignatureValue>

esta codigo es el que necesito extraer:

Dljl5RIE3XgLsI8jIKZzBBxDpLSAZ1wk3aoEiyGZrej0ZhLOZKfzhH5r5mx5pgdFwtznFca8iFW3/aGXqfHLUugvq8q7l6i0AnCYQHQBRIFzhPZpCws08v6A2eUjYI4h/g3DvAxjCYrEUtC8R6d32GKQt3SzCeYPf4+KQGRZL73xhce1wAzBiHp9GGX7OZEQfw4szeNLcvI1PQizXxe9SM/vUmWe+sgwPgAlaLNaeX4PQ3kmo7GDtxz1FoGi4Pccr3m8D3LuJq2hl2BgezV3uN8NJ38VhbEzjCGpoVG3sXuIDbXty10cv0Z0gjF7eTDyrwO3x1M24bz5S93fx+uQsg==

No he podido ni leer el archivo para mostrarlo y ver como puedo obtener ese id. Hasta el momento he intentado con estas opciones:

1.

$xml = 'archivo.xml';
      $DOM = new \DOMDocument('1.0', 'utf-8');
      $DOM->loadXML($xml);
      $datos = $DOM->getElementById('xmldsig-e038b730-632e-47e7-be42-6ca07c7b9e5b-sigvalue');
      foreach($datos as $dato) {
         foreach ($dato->attributes as $item) {

            $a = $item;
        
         }

      }
libxml_use_internal_errors(TRUE);
 
$objXmlDocument = simplexml_load_file("archivo.xml");
 
if ($objXmlDocument === FALSE) {
    echo "There were errors parsing the XML file.\n";
    foreach(libxml_get_errors() as $error) {
        echo $error->message;
    }
    exit;
}
 
$objJsonDocument = json_encode($objXmlDocument);
$arrOutput = json_decode($objJsonDocument, TRUE);
 
echo "<pre>";
print_r($objJsonDocument);

print_r($arrOutput);

3 respuestas 3

2

Debes usar el método:

DOMElement::getAttribute

Documentación:
https://www.php.net/manual/es/domelement.getattribute.php

Ejemplo:

- - - - - - - - - - - - - -
XML Data:
<data>
<Report ID="1">
    <Date>REVIEW</Date>
    <AuthorID>1</AuthorID>
</Report>
<Report ID="2">
    <Date>REVIEW</Date>
    <AuthorID>2</AuthorID>
</Report>
</data>
- - - - - - - - - - - - - -
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load( 'data.xml' );
$searchNode = $xmlDoc->getElementsByTagName( "Report" );
foreach( $searchNode as $searchNode )
{
    $valueID = $searchNode->getAttribute('ID');

    $xmlDate = $searchNode->getElementsByTagName( "Date" );
    $valueDate = $xmlDate->item(0)->nodeValue;

    $xmlAuthorID = $searchNode->getElementsByTagName( "AuthorID" );
    $valueAuthorID = $xmlAuthorID->item(0)->nodeValue;
   
    echo "$valueID - $valueDate - $valueAuthorID\n";
}
?>
- - - - - - - - - - - - - -
Output:
1 - REVIEW - 1
2 - REVIEW - 2
- - - - - - - - - - - - - -

el acceso a los namespaces es mediante:

<?php

$xml = <<<XML
<?xml version="1.0" standalone="yes"?>
<people xmlns:p="http://example.org/ns" xmlns:t="http://example.org/test">
    <p:person id="1">John Doe</p:person>
    <p:person id="2">Susie Q. Public</p:person>
</people>
XML;
 
$sxe = new SimpleXMLElement($xml);

$namespaces = $sxe->getNamespaces(true);
var_dump($namespaces);

?>

También puedes lograrlo con xpath:

$source = 'youtube.xml';

// load as file
$youtube = new SimpleXMLElement($source, null, true);
$youtube->registerXPathNamespace('yt', 'http://gdata.youtube.com/schemas/2007');

$count = 0;
foreach($youtube->entry as $item){

    //title works
    echo $item->title;

    $attributes = $item->xpath('//yt:duration/@seconds');
    echo $attributes[$count]['seconds'];
    $count++;
}

Aquí te dejo otro ejemplo:
https://stackoverflow.com/a/29877516/4717133

4
  • Gracias, pero he intentado asi: ds:SignatureValue y asi: SignatureValue. En la primera obtengo un error: Notice: Trying to get property 'nodeValue' of non-object y en la otra opción no sale nada.
    – Juanzu
    el 24 jun. 2021 a las 19:13
  • tienes que tomar en cuenta que leer un archivo XML no es lo mismo que leer un texto en formato XML y que cuando se trata de un archivo no debes usar el root como nodo inicial... simplemente comienzas desde el siguiente nodo.
    – user46896
    el 24 jun. 2021 a las 19:15
  • Si, tienes toda la razón pero la verdad no se como acceder a ese atributo en este tipo de archivo ya que son namespaces ds:nombre he intentado varias formas pero no logro conseguirlo, seguiré intentando..
    – Juanzu
    el 24 jun. 2021 a las 19:24
  • te acabo de agregar como se consigue los namespaces
    – user46896
    el 24 jun. 2021 a las 20:08
1

El xml no está bien formado, tiene algunos errores, por eso no lo has podido leer.

Por ejemplo, sobre el final del archivo se cierran estos tags que nunca han sido abiertos: "</cac:DocumentReference></cac:ParentDocumentLineReference>".

He modificado un poco el archivo xml, quizas puedo haber sacado tags de mas, pero la idea es que te sirva de ejemplo.

<AttachedDocument xmlns="urn:oasis:names:specification:ubl:schema:xsd:AttachedDocument-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ccts="urn:un:unece:uncefact:data:specification:CoreComponentTypeSchemaModule:2" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:xades="http://uri.etsi.org/01903/v1.3.2#" xmlns:xades141="http://uri.etsi.org/01903/v1.4.1#"><cbc:UBLVersionID>UBL 2.1</cbc:UBLVersionID><cbc:CustomizationID>Documentos adjuntos</cbc:CustomizationID><cbc:ProfileID>DIAN 2.1</cbc:ProfileID><cbc:ProfileExecutionID>1</cbc:ProfileExecutionID><cbc:ID>TD263479</cbc:ID><cbc:IssueDate>2021-05-31</cbc:IssueDate><cbc:IssueTime>21:47:50-05:00</cbc:IssueTime><cbc:DocumentType>Contenedor de Factura Electrónica</cbc:DocumentType><cbc:ParentDocumentID>TD263479</cbc:ParentDocumentID><cac:SenderParty><cac:PartyTaxScheme><cbc:RegistrationName>TODOMED LTDA</cbc:RegistrationName><cbc:CompanyID schemeAgencyID="195" schemeAgencyName="CO, DIAN (direccion)" schemeID="4" schemeName="31">815005074</cbc:CompanyID><cbc:TaxLevelCode listName="48">R-99-PN</cbc:TaxLevelCode><cac:TaxScheme><cbc:ID>01</cbc:ID><cbc:Name>IVA</cbc:Name></cac:TaxScheme></cac:PartyTaxScheme></cac:SenderParty><cac:ReceiverParty><cac:PartyTaxScheme><cbc:RegistrationName>CAJA DE COMPENSACION FAMILIAR DE NARIÑO</cbc:RegistrationName><cbc:CompanyID schemeAgencyID="195" schemeAgencyName="CO, DIAN (direccion)" schemeID="1" schemeName="31">891280008</cbc:CompanyID><cbc:TaxLevelCode listName="48">R-99-PN</cbc:TaxLevelCode><cac:TaxScheme><cbc:ID>01</cbc:ID><cbc:Name>IVA</cbc:Name></cac:TaxScheme></cac:PartyTaxScheme></cac:ReceiverParty><cac:Attachment><cac:ExternalReference><cbc:MimeCode>text/xml</cbc:MimeCode><cbc:EncodingCode>UTF-8</cbc:EncodingCode><cbc:Description><![CDATA[<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Invoice
    xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
    xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"
    xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
    xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
    xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2"
    xmlns:sts="dian:gov:co:facturaelectronica:Structures-2-1"
    xmlns:xades="http://uri.etsi.org/01903/v1.3.2#"
    xmlns:xades141="http://uri.etsi.org/01903/v1.4.1#"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd">
    <ext:UBLExtensions>
        <ext:UBLExtension>
            <ext:ExtensionContent>
                <sts:DianExtensions>
                    <sts:InvoiceControl>
                        <sts:InvoiceAuthorization>18764001534394</sts:InvoiceAuthorization>
                        <sts:AuthorizationPeriod>
                            <cbc:StartDate>2020-08-01</cbc:StartDate>
                            <cbc:EndDate>2021-08-01</cbc:EndDate>
                        </sts:AuthorizationPeriod>
                        <sts:AuthorizedInvoices>
                            <sts:Prefix>TD</sts:Prefix>
                            <sts:From>215000</sts:From>
                            <sts:To>275000</sts:To>
                        </sts:AuthorizedInvoices>
                    </sts:InvoiceControl>
                    <sts:InvoiceSource>
                        <cbc:IdentificationCode listAgencyID="6" listAgencyName="United Nations Economic Commission for Europe" listSchemeURI="urn:oasis:names:specification:ubl:codelist:gc:CountryIdentificationCode-2.1">CO</cbc:IdentificationCode>
                    </sts:InvoiceSource>
                    <sts:SoftwareProvider>
                        <sts:ProviderID schemeAgencyID="195" schemeAgencyName="CO, prueba (direccion)" schemeID="0" schemeName="31">890930534</sts:ProviderID>
                        <sts:SoftwareID schemeAgencyID="195" schemeAgencyName="CO, prueba (direccion)">49fab599-4556-4828-a30b-852a910c5bb1</sts:SoftwareID>
                    </sts:SoftwareProvider>
                    <sts:SoftwareSecurityCode schemeAgencyID="195" schemeAgencyName="CO, prueba (direccion)">596c04d8a5205efcc3b91ddb7d3d94d126c4c8e46188bb708438469eb8635b6c852c25cac5b9bd5b893d5c1419f5590f</sts:SoftwareSecurityCode>
                    <sts:AuthorizationProvider>
                        <sts:AuthorizationProviderID schemeAgencyID="195" schemeAgencyName="CO, prueba (direccion)" schemeID="4" schemeName="31">800197268</sts:AuthorizationProviderID>
                    </sts:AuthorizationProvider>
                    <sts:QRCode>NroFactura=EF7894
                        NitFacturador=815605074
                        NitAdquiriente=855995060
                        FechaFactura=2020-08-31
                        HoraFactura=15:57:06-05:00
                        ValorFactura=1000000.00
                        ValorIVA=0.00
                        ValorOtrosImpuestos=0.00
                        ValorTotalFactura=1000000.00
                     </sts:QRCode>
                </sts:DianExtensions>
            </ext:ExtensionContent>
        </ext:UBLExtension>
        <ext:UBLExtension>
            <ext:ExtensionContent>
                <ds:Signature Id="xmldsig-e038b630-632e-47e7-be42-6ca07c7b9e5b">
                    <ds:SignedInfo>
                        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
                        <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
                        <ds:Reference Id="xmldsig-e038b630-632e-47e7-be42-6ca07c7b9e5b-ref0" URI="">
                            <ds:Transforms>
                                <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                            </ds:Transforms>
                            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                            <ds:DigestValue>JJ97shgQUkoeAyw+N2/eLvXUf06WyAeFlRNOHxQOTZY=</ds:DigestValue>
                        </ds:Reference>
                        <ds:Reference URI="#xmldsig-e038b630-632e-47e7-be42-6ca07c7b9e5b-keyinfo">
                            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                            <ds:DigestValue>YU8ZKJQu2zrU3wI9u3jcCYv3rTB0rqGLy89oeJc0EHo=</ds:DigestValue>
                        </ds:Reference>
                        <ds:Reference Type="http://uri.etsi.org/01903#SignedProperties" URI="#xmldsig-e038b630-632e-47e7-be42-6ca07c7b9e5b-signedprops">
                            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                            <ds:DigestValue>dBCWb9NlJ7jJxXm8C7io1cbS042dRoYCO1oi0bKPCWU=</ds:DigestValue>
                        </ds:Reference>
                    </ds:SignedInfo>
                    <ds:SignatureValue Id="xmldsig-e038b730-632e-47e7-be42-6ca07c7b9e5b-sigvalue">Dljl5RIE3XgLsI8jIKZzBBxDpLSAZ1wk3aoEiyGZrej0ZhLOZKfzhH5r5mx5pgdFwtznFca8iFW3/aGXqfHLUugvq8q7l6i0AnCYQHQBRIFzhPZpCws08v6A2eUjYI4h/g3DvAxjCYrEUtC8R6d32GKQt3SzCeYPf4+KQGRZL73xhce1wAzBiHp9GGX7OZEQfw4szeNLcvI1PQizXxe9SM/vUmWe+sgwPgAlaLNaeX4PQ3kmo6GDtxz1FoGi4Pccr3m8D3LuJq2hl2BgezV3uN8NJ38VhbEzjCGpoVG3sXuIDbXty10cv0Z0gjF7eTDyrwO3x1M24bz5S93fx+uQsg==</ds:SignatureValue>
                </ds:Signature>
            </ext:ExtensionContent>
        </ext:UBLExtension>
    </ext:UBLExtensions>
</Invoice>]]></cbc:Description></cac:ExternalReference></cac:Attachment><cac:ResultOfVerification><cbc:ValidatorID>Unidad Especial direccion</cbc:ValidatorID><cbc:ValidationResultCode>02</cbc:ValidationResultCode><cbc:ValidationDate>2021-05-31</cbc:ValidationDate><cbc:ValidationTime>16:47:50-05:00</cbc:ValidationTime></cac:ResultOfVerification></AttachedDocument>

Código php:

Utilizo la función xpath para buscar el valor del nodo requerido.

  • "//": Selecciona nodos en el documento a partir del nodo actual que coinciden con la selección sin importar dónde se encuentren.
  • "@": Selecciona atributos.
//Id buscado (atributo del tag ds:SignatureValue)
$id = "xmldsig-e038b730-632e-47e7-be42-6ca07c7b9e5b-sigvalue";

$xml = simplexml_load_file('archivo.xml'); //path al archivo xml

$xmlInternoCadena = utf8_decode(current($xml->xpath("//cac:Attachment/cac:ExternalReference/cbc:Description")));

$xmlInterno = new SimpleXMLElement($xmlInternoCadena);

$signatureValue = utf8_decode(current($xmlInterno->xpath("//ds:Signature/ds:SignatureValue[@Id='{$id}']/text()")));

También puedes utilizar las rutas completas desde el nodo raiz o probar otras variantes para buscar el nodo que necesites.

2
  • Lo que sucede con mi archivo xml es que es muy largo y solo puse una parte ya que superar el limite de caracteres en stack. Gracias me ayudastes con la solución del problema.
    – Juanzu
    el 25 jun. 2021 a las 0:35
  • De nada @Juanzu! me alegra haberte ayudado. Después de haber posteado pensé en la posibilidad de que lo hayas acortado manualmente. Ten en cuenta que xpath puede retornar mas de un elemento (objeto SimpleXMLElement) de acuerdo al criterio utilizado para buscar, en cuyo caso deberás recorrer los elementos de arreglo que retorna en lugar de utilizar current() como si yo.
    – nachospiu
    el 25 jun. 2021 a las 12:19
0

esta función te sera de ayuda, yo la uso sin problemas actualmente

function desarmar_key_xml($xml,$key)
{
    $final=0;
    if($key=='PayableAmount')
    {   $porciones = explode($key, $xml);
        @$quitar_catro_finales = substr($porciones['1'], 0, -4);
        @$largo_cadena_key_inco=strlen($quitar_catro_finales);
        @$final = substr($quitar_catro_finales, 18, $largo_cadena_key_inco);
    }
    if($key=='UUID')
    {   $porciones = explode($key, $xml);
        @$quitar_catro_finales = substr($porciones['1'], 0, -4);
        @$largo_cadena_key_inco=strlen($quitar_catro_finales);
        @$final = substr($quitar_catro_finales, 38, $largo_cadena_key_inco);
    }
    if($key=='IssueDate')
    {   $porciones = explode($key, $xml);
        @$quitar_catro_finales = substr($porciones['1'], 0, -4);
        @$largo_cadena_key_inco=strlen($quitar_catro_finales);
        @$final = substr($quitar_catro_finales, 1, $largo_cadena_key_inco);
    }

    if($key=='schemeName="CUFE-SHA384">')
    {   
        $porciones = explode($key, $xml);
        $final=$porciones['1'];
        $porciones_dos = explode('</cbc:UUID>', $final);
        $final=$porciones_dos['0'];
    }
    
    if($key=='<cbc:IssueDate>')
    {   
        $porciones = explode($key, $xml);
        $final=$porciones['1'];
        $porciones_dos = explode('</cbc:IssueDate> ', $final);
        $final=$porciones_dos['0'];
    }

    if($key=='<cbc:IssueTime>')
    {   
        $porciones = explode($key, $xml);
        $final=$porciones['1'];
        $porciones_dos = explode('</cbc:IssueTime>', $final);
        $final=$porciones_dos['0'];
    }

    if($key=='<cbc:ID>')
    {   $porciones = explode($key, $xml);
        $final=$porciones['1'];
        $porciones_dos = explode('</cbc:ID>', $final);
        $final=$porciones_dos['0'];
    }

    if($key=='ID')
    {   $porciones = explode('<cbc:ID>', $xml);
        $final=$porciones['1'];
        $porciones_dos = explode('</cbc:ID>', $final);
        $final=$porciones_dos['0'];
    }
    return $final;
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.