1

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>
2
  • How looks exactly your xml file? Are attribute values enclosed between quotes? Commented Mar 8, 2017 at 12:02
  • I corrected the XML sample and improved the formatting, spelling, the title and the main question. Commented Mar 9, 2017 at 2:53

3 Answers 3

2

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
)
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to extract just id attribute values from <b> tags, try below XPath:

/a/b/@id

as /a//b[@id] means extracting all b elements that have id attribute and that are descendants of a

Comments

0

I feel like both existing answers tell you half of what you need to know.

Firstly, your XPath is subtly wrong: b[@id] means "any b element which has an attribute id". You want instead b/@id, meaning "any id attribute which is a child of a b element".

Secondly, the SimpleXML xpath method returns an array of SimpleXMLElement objects representing the elements or attributes matched. To get just the text contents of those attributes, you need to cast each one to string, using (string)$foo.

So:

$xmlfile = simplexml_load_file("test.xml");
$test = $xmlfile->xpath("/a//b/@id");
$list = [];
foreach ( $test as $attr ) {
    $list[] = (string)$attr;
}

[Live Demo]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.