Viewed   58 times

I am trying to use SimpleXML in PHP to loop through a XML object - the object format is below:-

I get the following error when I try to get the element tags by name - can anyone explain what I am doing wrong?

Call to undefined method SimpleXMLElement::getElementsByTagName() on ...

Below is the XML file I am reading from:

<?xml version="1.0" encoding="utf-8"?>
<response>
    <products>
        <item>
            <product_id>32417</product_id>
            <manufacturer>Alcatel</manufacturer>
            <model>Sparq 2</model>
            <deeplink>http://www.mysite.com/sc_offer?gid=32417</deeplink>
            <thumbnail_URL>http://www.mysite.com/images/devices/thumbs/Alcatel-Sparq-II.jpg</thumbnail_URL>
            <image_URL>http://www.mysite.com/images/devices/Alcatel-Sparq-II.jpg</image_URL>
            <price_not_working>0.00</price_not_working>
            <price_poor>0.00</price_poor>
            <price_fair>20.00</price_fair>
            <price_good>25.00</price_good>
            <price_perfect>25.00</price_perfect>
            <price_new>25.00</price_new>
            <battery_new>1.00</battery_new>
            <battery_perfect>1.00</battery_perfect>
            <battery_good>1.00</battery_good>
            <battery_fair>1.00</battery_fair>
            <battery_poor>0.00</battery_poor>
            <charger_new>1.00</charger_new>
            <charger_perfect>1.00</charger_perfect>
            <charger_good>1.00</charger_good>
            <charger_fair>1.00</charger_fair>
            <charger_poor>0.00</charger_poor>
            <packaging_new>1.00</packaging_new>
            <packaging_perfect>1.00</packaging_perfect>
            <packaging_good>1.00</packaging_good>
            <packaging_fair>1.00</packaging_fair>
            <packaging_poor>0.00</packaging_poor>
        </item>
        <item>
            <product_id>31303</product_id>
            <manufacturer>Apple</manufacturer>
            <model>iPhone 3G 8gb</model>
            <deeplink>http://www.mysite.com/sc_offer?gid=31303</deeplink>
            <thumbnail_URL>http://www.mysite.com/images/devices/thumbs/iPhone 8 3G.jpg</thumbnail_URL>
            <image_URL>http://www.mysite.com/images/devices/iPhone 8 3G.jpg</image_URL>
            <price_not_working>0.00</price_not_working>
            <price_poor>0.00</price_poor>
            <price_fair>7.00</price_fair>
            <price_good>2.00</price_good>
            <price_perfect>2.00</price_perfect>
            <price_new>2.00</price_new>
            <battery_new>1.00</battery_new>
            <battery_perfect>1.00</battery_perfect>
            <battery_good>1.00</battery_good>
            <battery_fair>1.00</battery_fair>
            <battery_poor>0.00</battery_poor>
            <charger_new>1.00</charger_new>
            <charger_perfect>1.00</charger_perfect>
            <charger_good>1.00</charger_good>
            <charger_fair>1.00</charger_fair>
            <charger_poor>0.00</charger_poor>
            <packaging_new>1.00</packaging_new>
            <packaging_perfect>1.00</packaging_perfect>
            <packaging_good>1.00</packaging_good>
            <packaging_fair>1.00</packaging_fair>
            <packaging_poor>0.00</packaging_poor>
        </item>
    </products>
</response>

My PHP code is below:

$devices = $xml->getElementsByTagName( "response" ); // error on this line

I am trying to make devices an array so I can use the data in a foreach loop.

 Answers

4

SimpleXML doesn't have a getElementsByTagName() method (DOMDocument does).

In SimpleXML, the object (e.g $xml) is treated as the root element. So you can loop through the product items like so:

$xml = simplexml_load_string($xmlString);
foreach($xml->products->item as $item)
{
    echo (string)$item->product_id;
    echo (string)$item->model;
}

Example of building a devices associative array:

$devices = array();

$xml = simplexml_load_string($xmlString);
foreach($xml->products->item as $item)
{
   $device = array();

   foreach($item as $key => $value)
   {
        $device[(string)$key] = (string)$value;
   }

   $devices[] = $device;
}

print_r($devices);

Outputs:

Array
(
    [0] => Array
        (
            [product_id] => 32417
            [manufacturer] => Alcatel
            [model] => Sparq 2
            [deeplink] => http://www.mysite.com/sc_offer?gid=32417
            [thumbnail_URL] => http://www.mysite.com/images/devices/thumbs/Alcatel-Sparq-II.jpg
            [image_URL] => http://www.mysite.com/images/devices/Alcatel-Sparq-II.jpg
            [price_not_working] => 0.00
            [price_poor] => 0.00
            [price_fair] => 20.00
            [price_good] => 25.00
            [price_perfect] => 25.00
            [price_new] => 25.00
            [battery_new] => 1.00
            [battery_perfect] => 1.00
            [battery_good] => 1.00
            [battery_fair] => 1.00
            [battery_poor] => 0.00
            [charger_new] => 1.00
            [charger_perfect] => 1.00
            [charger_good] => 1.00
            [charger_fair] => 1.00
            [charger_poor] => 0.00
            [packaging_new] => 1.00
            [packaging_perfect] => 1.00
            [packaging_good] => 1.00
            [packaging_fair] => 1.00
            [packaging_poor] => 0.00
        )

    [1] => Array
        (
            [product_id] => 31303
            [manufacturer] => Apple
            [model] => iPhone 3G 8gb
            [deeplink] => http://www.mysite.com/sc_offer?gid=31303
            [thumbnail_URL] => http://www.mysite.com/images/devices/thumbs/iPhone 8 3G.jpg
            [image_URL] => http://www.mysite.com/images/devices/iPhone 8 3G.jpg
            [price_not_working] => 0.00
            [price_poor] => 0.00
            [price_fair] => 7.00
            [price_good] => 2.00
            [price_perfect] => 2.00
            [price_new] => 2.00
            [battery_new] => 1.00
            [battery_perfect] => 1.00
            [battery_good] => 1.00
            [battery_fair] => 1.00
            [battery_poor] => 0.00
            [charger_new] => 1.00
            [charger_perfect] => 1.00
            [charger_good] => 1.00
            [charger_fair] => 1.00
            [charger_poor] => 0.00
            [packaging_new] => 1.00
            [packaging_perfect] => 1.00
            [packaging_good] => 1.00
            [packaging_fair] => 1.00
            [packaging_poor] => 0.00
        )

)
Thursday, December 15, 2022
2

Sure you can. Eg.

<?php
$newsXML = new SimpleXMLElement("<news></news>");
$newsXML->addAttribute('newsPagePrefix', 'value goes here');
$newsIntro = $newsXML->addChild('content');
$newsIntro->addAttribute('type', 'latest');
Header('Content-type: text/xml');
echo $newsXML->asXML();
?>

Output

<?xml version="1.0"?>
<news newsPagePrefix="value goes here">
    <content type="latest"/>
</news>

Have fun.

Saturday, September 10, 2022
3

So basically what you need to do is a function that takes each <asset/> child of current node, builds the HTML then checks if the current node has <asset/> children of its own and keeps recursing deeper down the tree.

Here's how you can do it:

function printAssetMap()
{
    return printAssets(simplexml_load_file(X_ASSETS));
}

function printAssets(SimpleXMLElement $parent)
{
    $html = "<ul>n";
    foreach ($parent->asset as $asset)
    {
        $html .= printAsset($asset);
    }
    $html .= "</ul>n";

    return $html;
}

function printAsset(SimpleXMLElement $asset)
{
    $html = '<li id="asset'.$asset->asset_assetid.'"><ins>&nbsp;</ins><a href="#">'.$asset->asset_name.' ['.$asset->asset_assetid.']</a>';

    if (isset($asset->asset))
    {
        // has <asset/> children
        $html .= printAssets($asset);
    }

    $html .= "</li>n";

    return $html;
}

By the way, I would expect a function named "printX" to actually print or echo something, rather than return it. Perhaps you should name those functions "buildX" ?

Saturday, September 17, 2022
 
shdr
 
2

You will have to register the namespaces on each element you want to use them:

$xml= new SimpleXMLElement("86553893.xml");
$xml->registerXpathNamespace('com', 'http://www.wipo.int/standards/XMLSchema/Common/1');
foreach ($xml->xpath('//com:ApplicationNumber') as $event) {
  $event->registerXpathNamespace(
    'com', 'http://www.wipo.int/standards/XMLSchema/Common/1'
  );                         
  var_export($event->xpath('com:ApplicationNumberText'));
}

This is different in DOM, you use an DOMXPath instance, so it is only a single object and you will have to register the namespaces only once.

$dom = new DOMDocument();
$dom->load("86553893.xml");
$xpath = new DOMXpath($dom);
$xpath->registerNamespace('com', 'http://www.wipo.int/standards/XMLSchema/Common/1');

foreach ($xpath->evaluate('//com:ApplicationNumber') as $event) {
  var_export($xpath->evaluate('string(com:ApplicationNumberText)', $event));
}
Saturday, September 10, 2022
 
4

Using recursion, you can create a brand new document based on the input, solving all your points at once:

Code

<?php

$input = file_get_contents('http://www.fluffyduck.com.au/sampleXML.xml');
$inputDoc = new DOMDocument();
$inputDoc->loadXML($input);

$outputDoc = new DOMDocument("1.0", "utf-8");
$outputDoc->appendChild($outputDoc->createElement("root"));

function ConvertUserToItem($outputDoc, $inputNode, $outputNode)
{
    if ($inputNode->hasChildNodes())
    {
        foreach ($inputNode->childNodes as $inputChild)
        {
            if (strtolower($inputChild->nodeName) == "user")
            {
                $outputChild = $outputDoc->createElement("item");
                $outputNode->appendChild($outputChild);
                // read input attributes and convert them to nodes
                if ($inputChild->hasAttributes())
                {
                    $outputContent = $outputDoc->createElement("content");
                    foreach ($inputChild->attributes as $attribute)
                    {
                        if (strtolower($attribute->name) != "id")
                        {
                            $outputContent->appendChild($outputDoc->createElement($attribute->name, $attribute->value));
                        }
                        else
                        {
                            $outputChild->setAttribute($attribute->name, $attribute->value);
                        }
                    }               
                    $outputChild->appendChild($outputContent);
                }
                // recursive call
                ConvertUserToItem($outputDoc, $inputChild, $outputChild);
            }
        }
    }
}

ConvertUserToItem($outputDoc, $inputDoc->documentElement, $outputDoc->documentElement);

header("Content-Type: text/xml; charset=" . $outputDoc->encoding);
echo $outputDoc->saveXML();
?>

Output

<?xml version="1.0" encoding="utf-8"?>
<root>
    <item id="41">
        <content>
            <username>bsmain</username>
            <firstname>Boss</firstname>
            <lastname>MyTest</lastname>
            <fullname>Test Name</fullname>
            <email>lalal@test.com</email>
            <logins>1964</logins>
            <lastseen>11/09/2012</lastseen>
        </content>
        <item id="61">
            <content>
                <username>underling</username>
                <firstname>Under</firstname>
                <lastname>MyTest</lastname>
                <fullname>Test Name</fullname>
                <email>lalal@test.com</email>
                <logins>4</logins>
                <lastseen>08/09/2009</lastseen>
            </content>
        </item>
...
Friday, December 9, 2022
 
petele
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :