Search code examples
phpxmlgetelementsbytagname

Get attribute of <?xml-stylesheet ... ?> with PHP


I have this, in an XML file :

<?xml-stylesheet href="../StyleSheets/VDD11.xsl" type="text/xsl"?>

I want to get the value of this attribute : href="". I'm working with PHP 5. I've tried this code, but don't want to work :

function find_XSL_Fiche($file)
{
    $xml = new DOMDocument();
    $xml->load($file);
    echo $file.'<br />';
    $searchNode = $xml->getElementsByTagName( "xml-stylesheet" );
    $xsl = "";
    foreach ($searchNode as $searchNode)
    {
        $xsl = $searchNode->getAttribute('href'); 
    }
    echo $xsl;
    return $xsl;
}

At the end, i want to get ../StyleSheets/VDD11.xsl

Thanx


Solution

  • This is a processing instruction node. You can use Xpath to fetch it:

    Fetch all processing instruction nodes:
    //processing-instruction()

    Filtered by name:
    //processing-instruction()[name() = "xml-stylesheet"]

    Cast the first found PI to a string:
    string(//processing-instruction()[name() = "xml-stylesheet"])

    $dom = new DOMDocument();
    $dom->loadXml(
     '<?xml version="1.0"?><?xml-stylesheet href="../StyleSheets/VDD11.xsl" type="text/xsl"?><xml/>'
    );
    $xpath = new DOMXpath($dom);
    
    var_dump(
      $xpath->evaluate(
        'string(//processing-instruction()[name() = "xml-stylesheet"])'
      )
    );
    

    Output: https://eval.in/171053

    string(47) "href="../StyleSheets/VDD11.xsl" type="text/xsl""
    

    The content of a PI is text, it has no fixed structure. So you need to parse the data manually from the result using string functions or PCRE.