Php 如何使用一个XPath来设置两个字段?

Php 如何使用一个XPath来设置两个字段?,php,parsing,xpath,xml-parsing,Php,Parsing,Xpath,Xml Parsing,我有一个XPath,它获取我想要读取的div。如何用一个XPath读取div的类和名称?load('>'); <?php $xmlDoc = new DOMDocument(); $xmlDoc->load( '<<your file>>>' ); //$xmlDoc->loadHTML($sourceString); //-> if its a string you have $

我有一个XPath,它获取我想要读取的div。如何用一个XPath读取div的类和名称?

load('>');
<?php 
        $xmlDoc = new DOMDocument(); 
        $xmlDoc->load( '<<your file>>>' ); 
    //$xmlDoc->loadHTML($sourceString); //-> if its a string you have
        $xpath = new DOMXpath($doc);
        $elements = $xpath->query("Your XPath");

        //if you are sure there is only one div, for the Xpath, you can use a index 0 in the next statement, else uou have to itereate it in a loop

    $node = $elements->item(0);

    $attrib1 = $node->attributes->getNamedItem("<attribute_name1>");
    $attrib2 = $node->attributes->getNamedItem("<attribute_name2>");
    $attrib3 = $node->attributes->getNamedItem("<attribute_name3>");
    ....



        ?> 
//$xmlDoc->loadHTML($sourceString);//->如果你有一根绳子 $xpath=新的DOMXpath($doc); $elements=$xpath->query(“您的xpath”); //如果确定只有一个div,那么对于Xpath,可以在下一条语句中使用索引0,否则必须在循环中创建它 $node=$elements->item(0); $attrib1=$node->attributes->getNamedItem(“”); $attrib2=$node->attributes->getNamedItem(“”); $attrib3=$node->attributes->getNamedItem(“”); .... ?>
此代码选择具有属性name和class的所有div。请参见下文,了解如何从所选节点中选择信息

<?php

    $xmlstring = '<root>' .
        '<div name="value1" class="value2" myarg="value3"></div>' .
        '<div name="value4"></div>' .
    '</root>';
    $xml = simplexml_load_string($xmlstring);

    // Select all div's that have attributes name and class
    $xpath = "//div[@name and @class]"; 
    var_dump($result = $xml->xpath($xpath));

    /* Outputs:
        array(1) {
          [0]=>
          object(SimpleXMLElement)#3 (1) {
            ["@attributes"]=>
            array(3) {
              ["name"]=>
              string(6) "value1"
              ["class"]=>
              string(6) "value2"
              ["myarg"]=>
              string(6) "value3"
            }
          }
        }   
    */

    // note that only one iteration is performed
    // as the second div does not have an attribut
    // called 'class'.
    foreach($result as $element)
    {
        echo $element['name'];   // value1
        echo $element['class'];  // value2
    } 

    // or, if only one div is present in the document:
    echo $result[0]['name'];     // value1
    echo $result[0]['class'];    // value2  

?>

可能重复:@GeneSys Well。。如果您认为所有XPath问题都是重复的,那么请回答“是”。