简体   繁体   中英

PHP XML get children variables from parent using namespaces

How do i get abcde from the below xml markup...

<api:field name="test">
    <api:text>a</api:text>
    <api:text>b</api:text>
    <api:text>c</api:text>
    <api:text>d</api:text>
    <api:text>e</api:text>
</api:field>

I am trying to use this for loop:

foreach ($xml->xpath('//api:field[@name="test"]') as $item)
{
    foreach ($item->children() as $child) {
        ...
    }
}

but i do not know how to access the child nodes which contain no attributes.

I need to get the child values for the parent node "test" specifically so please don't give me $xml->xpath("//api:text"); as an answer. The problem with this answer is that we might see under other parent nodes and i only want to get the child values from a specific parent node. In this case name="test" .

There are a couple of ways you can achieve this. Either just extend your xpath expression to return the child nodes themselves:

foreach ($sxml->xpath('/api:field[@name="test"]/api:text') as $item) {
    echo (string) $item, PHP_EOL;
}

Alternatively if you did want to use two loops (or it just better fits your use case), you just need to pass the namespace prefix into the children() method:

foreach ($sxml->xpath('/api:field[@name="test"]') as $item) {
    foreach ($item->children('api', true) as $child) {
        echo (string) $child, PHP_EOL;
    }
}

(If the namespace prefix is likely to change, you can use the registerXPathNamespace method to register a persistent one, according to the defined namespace URL.)

Both of these approaches will yield the same result:

a
b
c
d
e

See https://eval.in/954569 for a full example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM