1

Hey I have a problem with Simple DOM parser which is driving me nuts.

This works OK:

foreach($html->find('input[name=sex]') as $e)
echo $e->value;

Even if its only 1 result.

However this doesn't work:

echo $html->find('input[name=sex]')->value;

I don't want really use foreach because I expect only 1 result. So someone could help me with second block of code?

Cheers

1
  • ->find() returns a results object, which can be boiled to an array of matching elements. You're doing ->value on the whole array, instead of one of the actual elements. Commented Oct 20, 2011 at 19:45

3 Answers 3

4

According to the docs, the second parameter is the index you wish to find. Set that to 0 to return the first (0th) element rather than an array of objects:

Find elements by the CSS selector. Returns the Nth element object if index is set, otherwise return an array of object.

$html->find('input[name=sex]', 0)->value;
Sign up to request clarification or add additional context in comments.

Comments

0
$html->find('input[name=sex]')[0]->value;

It seems find returns an array so using index would help you.

Use the code above.

2 Comments

This kind of array dereferencing is not available before PHP 5.4
Then he can do the logic and use the property after assigning it to the variable first.
0

If you can use for-each on something, it is an array/collection, even if there is one element. You are asking to echo an entire array, for which which may need print_r. As another poster suggested, use a subscript.

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.