PHP中的xPath属性值

时间:2014-01-17 14:48:50

标签: php xml xpath

我尝试使用xPath从XML获取attrbiute和数据。 我不能'得到属性。

XML:

<table:table-row>
    <table:table-cell table:style-name="Tabella1.A2" office:value-type="string">
        <text:p text:style-name="Standard">RAG. SOC.:</text:p>
    </table:table-cell>
    <table:table-cell table:style-name="Tabella1.B2" office:value-type="string">
        <text:p text:style-name="Standard">
            <text:database-display text:table-name="portale.anaTanagrafica" text:table-type="table" text:column-name="ana_rag_sociale" text:database-name="Nuovo database">&lt;ana_rag_sociale&gt;</text:database-display>
        </text:p>
    </table:table-cell>
</table:table-row>

和PHP函数:

$path = "//text:database-display";        
if ($xml !== FALSE) {
    foreach($xml->xpath($path) as $agenzia) {
        FB::INFO("Nodo: " . $agenzia);
        FB::INFO("Nodo: " . $agenzia[@"text:table-name"]);
    } 
}

我想要的是以下输出:

Nodo: &lt;ana_rag_sociale&gt;
Nodo: portale.anaTanagrafica

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要使用SimpleXML注册命名空间:

$xml->registerXPathNamespace('text', 'youractualtextnamespace');

完成后,有几种方法可以访问您想要的数据。这是一个完整的例子:

$string = <<<XML
<table:table-row xmlns:table="youractualnamespace"
    xmlns:office="youractualofficenamespace" xmlns:text="youractualtextnamespace">
    <table:table-cell table:style-name="Tabella1.A2"
        office:value-type="string">
        <text:p text:style-name="Standard">RAG. SOC.:</text:p>
    </table:table-cell>
    <table:table-cell table:style-name="Tabella1.B2"
        office:value-type="string">
        <text:p text:style-name="Standard">
            <text:database-display text:table-name="portale.anaTanagrafica"
                text:table-type="table" text:column-name="ana_rag_sociale"
                text:database-name="Nuovo database">&lt;ana_rag_sociale&gt;</text:database-display>
        </text:p>
    </table:table-cell>
</table:table-row>
XML;

$path = "//text:database-display";
$xml = new SimpleXMLElement($string);
$xml->registerXPathNamespace('text', 'youractualtextnamespace');
if ($xml !== FALSE) {
    foreach($xml->xpath($path) as $agenzia) {
        $attr = $agenzia->xpath("@text:table-name");
        print("Nodo: " . $agenzia);
        print("Nodo: " . $attr[0]);
    }
}