Search code examples
phparraysxmlxpathsimplexml

SimpleXML: Add XML attribute values to an array


I want to create an array from the id attributes of the element <b>, however the below code returns all XML.

PHP file:

$xmlfile=simplexml_load_file("test.xml");
$test=$xmlfile->xpath("/a//b[@id]");

XML file(fixed):

<a>
  <b id="1"></b>
  <b id="2"></b>
  <b id="3"></b>
  <b id="4"></b>
  <b id="5"></b>
</a>

Solution

  • Hello_ mate

    If I understood you right this code snippet will do the job:

    SOLUTION 1

    $xmlfile = simplexml_load_file("test.xml");
    $items = $xmlfile->xpath("/a//b[@id]");
    
    $result = array();
    foreach ($items as $item) {
        $result[] = $item['id']->__toString();
    }
    
    echo '<pre>' . print_r($result, true) . '</pre>';
    exit;
    
    // Output
    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
    )
    

    SOLUTION 2

    $sampleHtml = file_get_contents("test.xml");
    
    $result = array();
    $dom = new \DOMDocument();
    if ($dom->loadHTML($sampleHtml)) {
        $bElements = $dom->getElementsByTagName('b');
        foreach ($bElements as $b) {
            $result[] = $b->getAttribute('id');
        }
    } else {
        echo 'Error';
    }
    
    echo '<pre>' . print_r($result, true) . '</pre>';
    exit;
    
    // Output
    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
    )