0
votes

Consider the following XML document:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <product code="WERGTR">
    </product>
    <product code="HERGGFH">
    </product>
    <product code="NYTERBT">
    </product>
    <product code="NUYRTHT">
    </product>
    <misc>
        <copyrightHTML>Somo stuff</copyrightHTML>
        <categoryLink name="Attr1">http://www.example.com/val1</categoryLink>
        <categoryLink name="Attr2">http://www.example.com/val2</categoryLink>
        <categoryLink name="Attr3">http://www.example.com/val3</categoryLink>
        <categoryLink name="Attr4">http://www.example.com/val4</categoryLink>
    </misc>
</catalog>

How can I echo each <categoryLink> element? Displaying its value and attribute name value?

I've tried using

$pricesDatabase = "http://www.example.com/database.xml";
$xml = simplexml_load_file($pricesDatabase) or die("Couldn't create database.xml");

foreach($xml->children() as $links) { 
    echo $links->categoryLink['name'];
    echo "<br>"; 
}

But doesn't work, it simply shows nothing.

The result I'm looking for could be as below:

$key . ": value: " . $value . ", name: " . $nameValue

So...

[0]: value: http://www.example.com/val1, name: Attr1
[1]: value: http://www.example.com/val2, name: Attr2
[2]: value: http://www.example.com/val3, name: Attr3
[3]: value: http://www.example.com/val4, name: Attr4
2

2 Answers

1
votes

Actually the output is:

<br><br><br><br>Attr1<br>

$xml is associated with the document element node catalog. Its children would be product and misc. The first four '
' are from the product nodes, the last is the misc nodes. You're accessing the first categoryLink child and its attribute name.

foreach($xml->misc->categoryLink as $link) { 
    echo $link['name'], ', ', $link;
    echo "\n"; 
}

Or using Xpath:

foreach($xml->xpath('misc/categoryLink') as $link) { 
    echo $link['name'], ', ', $link;
    echo "\n"; 
}

SimpleXMLElement objects behave different depending how they are used, you can iterate over several nodes with the same name, access the first of the list or cast it to string to get the text content.

0
votes

I've figured how to:

1.- Get the value of name attribute for each <categoryLink> element:

foreach($xml->xpath('//misc/categoryLink/@name') as $nameAttr) {
    echo $nameAttr . "<br>"; 
}

2.- Get the value of each <categoryLink> element:

foreach($xml->xpath('//misc/categoryLink') as $linkVal) {
    echo $linkVal . "<br>"; 
}

The downside is I haven't figured out how to output both values in each line.