Search code examples
phpxmlget

How to get the xml sub-parameters


How to get the xml sub-parameters? how to get all the results of category and return a result $category .. category = Test1, Test2

my xml

<xml>
<title>Test 123</title>
<categories>
<category>Test1</category>
<category>Test2</category>
</categories>
</xml>

my get code

$category = htmlspecialchars($item->categories->category, ENT_XML1 | ENT_QUOTES, 'UTF-8');

echo $category; //I want to return Test1, Test2

Solution

  • You could loop $item->categories->category using a foreach:

    $source = <<<DATA
    <xml>
    <title>Test 123</title>
    <categories>
    <category>Test1</category>
    <category>Test2</category>
    </categories>
    </xml>
    DATA;
    
    $item = simplexml_load_string($source);
    
    foreach ($item->categories->category as $elm) {
        echo $elm . PHP_EOL;
    }
    

    That will give you:

    Test1
    Test2
    

    See a php demo