Fetch specific tag with an attribute value from XML

前端 未结 2 1349
故里飘歌
故里飘歌 2020-12-22 14:01

I have a XML file like the following:



    &         


        
相关标签:
2条回答
  • 2020-12-22 14:24

    All you need to do is just create DOMDocument object, load your xml, create DOMXpath object for your document and evaluate xpath expression:

    $xml = file_get_contents( "https://crm.zoho.com/crm/private/xml/SalesOrders/getRecords?authtoken=XXX&scope=crmapi" );
    
    $doc = new DOMDocument();
    $doc->loadXML( $xml );
    
    $xpath = new DOMXPath( $doc );
    $items = $xpath->evaluate( '//FL[@val="Sales Order Owner"]' );
    for ( $i = 0; $i < $items->length; $i++ ) {
        echo $items->item( $i )->textContent . '<br>';
    }
    

    It will output:

    Adithya Buddhavarapu
    Adithya Buddhavarapu
    Adithya Buddhavarapu
    Adithya Buddhavarapu
    
    0 讨论(0)
  • 2020-12-22 14:34

    You best express that with an Xpath expression:

    $owner = ($nodes = $xml_sales->xpath('//FL[@val = "Sales Order Owner"][1]')) 
             ? (string) $nodes[0] 
             : NULL;
    

    This will give:

    Adithya Buddhavarapu
    

    in your case. If the element is not found it is NULL.

    //FL[@val = "Sales Order Owner"][1]
    

    This is the xpath expression. It reads:

    Take any FL element of the document that has the val attribute with the value "Sales Order Owner" that is the first element ([1]).

    If you need that per row, it works similar, just run the xpath per row. See SimpleXMLElement::xpath.

    0 讨论(0)
提交回复
热议问题